473,748 Members | 11,145 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

derived class pointer to base class object

Hi Everyone,

I was just playing around virtual functions and landed up with the
following,

class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};

class Derived1: public Base1
{
public: void sample()
{
printf("derived ::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);
}

this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?

Thanks in advance!!!
Dec 3 '07 #1
13 4928
Rahul wrote:
I was just playing around virtual functions and landed up with the
following,

class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};

class Derived1: public Base1
{
public: void sample()
{
printf("derived ::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);
}

this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?
The code 'ptr->sample()' has undefined behaviour because casting from
a base class to a derived class is NOT what 'reinterpret_ca st' is for.
Either 'static_cast' or 'dynamic_cast' are used for that.

In your case 'dynamic_cast' should return NULL since the object is
NOT of type 'derived', which should suggest that 'static_cast' is not
what you need either. You only use 'static_cast' in this situation
if you *know exactly* that the pointer was obtained by converting
some derived class object into the base.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 3 '07 #2
On 2007-12-03 11:27:57 -0500, "Victor Bazarov" <v.********@com Acast.netsaid:
Rahul wrote:
>I was just playing around virtual functions and landed up with the
following,

class Base1
{
public: virtual void sample()
{
printf("base:: sample\n");
};
};

class Derived1: public Base1
{
public: void sample()
{
printf("derive d::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);
}

this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?

The code 'ptr->sample()' has undefined behaviour because casting from
a base class to a derived class is NOT what 'reinterpret_ca st' is for.
Either 'static_cast' or 'dynamic_cast' are used for that.

In your case 'dynamic_cast' should return NULL since the object is
NOT of type 'derived', which should suggest that 'static_cast' is not
what you need either. You only use 'static_cast' in this situation
if you *know exactly* that the pointer was obtained by converting
some derived class object into the base.
And just to complete the circle: replacing reinterpret_cas t with
static_cast in the original code still results in undefined behavior.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Dec 3 '07 #3
On Dec 3, 9:27 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Rahul wrote:
I was just playing around virtual functions and landed up with the
following,
class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};
class Derived1: public Base1
{
public: void sample()
{
printf("derived ::sample\n");
};
};
int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);
}
this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?

The code 'ptr->sample()' has undefined behaviour because casting from
a base class to a derived class is NOT what 'reinterpret_ca st' is for.
Either 'static_cast' or 'dynamic_cast' are used for that.

In your case 'dynamic_cast' should return NULL since the object is
NOT of type 'derived', which should suggest that 'static_cast' is not
what you need either. You only use 'static_cast' in this situation
if you *know exactly* that the pointer was obtained by converting
some derived class object into the base.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Then, how do you suggest to type cast from Base class object to
derived class pointer?
Dec 3 '07 #4
Rahul wrote:
On Dec 3, 9:27 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>Rahul wrote:
>> I was just playing around virtual functions and landed up with the
following,
>>class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};
>> class Derived1: public Base1
{
public: void sample()
{
printf("derived ::sample\n");
};
};
>>int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);
}
>>this invokes the sample() of base version, but if i declare sample
as a ordinay (non-virtual) function, the sample() of derived class
is invoked. I'm wondering how? Can anyone help in this regard?

The code 'ptr->sample()' has undefined behaviour because casting from
a base class to a derived class is NOT what 'reinterpret_ca st' is
for. Either 'static_cast' or 'dynamic_cast' are used for that.

In your case 'dynamic_cast' should return NULL since the object is
NOT of type 'derived', which should suggest that 'static_cast' is not
what you need either. You only use 'static_cast' in this situation
if you *know exactly* that the pointer was obtained by converting
some derived class object into the base.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask

Then, how do you suggest to type cast from Base class object to
derived class pointer?
I am not really sure how to tell you this... Have you been reading
what I wrote? You can only do it using 'dynamic_cast' or 'static_cast'.
However, in your case, since the object you originally create is NOT
of the derived class, 'dynamic_cast' will fail (return NULL) and
'static_cast' has undefined behaviour.

*I suggest* you _don't_ cast the pointer to the base class to
a pointer to derived class when there is *no reason for it*.

If you need an object of the derived class, create an object of that
type. Then you can convert its address to the pointer of the base
class and later 'static_cast' it back to the same derived class.

What is the problem you're trying to solve?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 3 '07 #5
Rahul wrote:
...
Then, how do you suggest to type cast from Base class object to
derived class pointer?
If all you have is a standalone base class object (as in your original
code sample), then you sinly DON'T cast it to the derived type. Why on
earth would you want to do something like that?

If, on the other hand, you have a pointer to a base class _subobject_
within an object of derived class, then you can downcast that pointer
using 'static_cast' or 'dynamic_cast'.

--
Best regards,
Andrey Tarasevich
Dec 3 '07 #6
[snip]
>
Then, how do you suggest to type cast from Base class object to
derived class pointer?

Let me try and clarify the problem. Suppose Derived class has some
data in it like int x. Suppose Base class does not. Now:

you create an instance of the base class
you want a pointer to derived class
so, you tryed to cast a pointer from base to derived

Now STOP: Ask how is the compiler (or the program at run time)
supposed to know what to set int x to? It has no idea! That is the
source of your problem in attempting to cast in the wrong direction.

A derived class does not have everything it needs to make a base
class, but a base class only has "part" of what a derived class needs.

Because, most of the time the entire purpose of making a derived class
is to EXTEND the base. thusly, by extending, you add new things.

Now, if you really needed to cast from base to derived for some
reason, then you would need to implement some "factory" or method to
which additional data (if it exists in derived) can be supplied and
implement some logic to have it return an instance of the desired
type. Not a casted pointer, but more likely a new instance or a
pointer to a new instance.
Dec 3 '07 #7
[snip
A derived class does not have everything it needs to make a base
class, but a base class only has "part" of what a derived class needs.
[snip]

edit typo: A derived class DOES have everything it needs to make a
base class, but a base class only has "part" of what it needs to make
a derived class.
Dec 3 '07 #8
Rahul wrote:
I was just playing around virtual functions and landed up with the
following,

class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};
Besides other comments this base class is missing a virtual destructor.
Dec 4 '07 #9
On Dec 3, 6:23 pm, Rahul <sam_...@yahoo. co.inwrote:
Hi Everyone,

I was just playing around virtual functions and landed up with the
following,

class Base1
{
public: virtual void sample()
{
printf("base::s ample\n");
};
};

class Derived1: public Base1
{
public: void sample()
{
printf("derived ::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cas t<Derived1 *(new Base1());
ptr->sample();
return(0);

}

this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?

Thanks in advance!!!
In first case (with virtual method) both classes have pointer to
virtual method table.
With reinterpret_cst you say to compiler to work with Base, as it has
memory layout as Derived class.
When you call ptr->sample() you do following :
1)get pointer to virtual table of the class ( which has the same place
in the object memory for Base and Derive, but different value)
2)call the first ( as Derived has single virtual method as Base does)
method from virtual table, which is Base::Sample.

If you remove virtual method from base class, both will not have any
pointer to virtual method table.So
When you call ptr->sample() you do following :
1)Get the address of Derived::sample and run it successfully, because
it doesn't refer to any of Derived members or methods

P.S. Some assumptions regarding second step, correct me please, if i'm
wrong :
There is special table for Derived methods ( for non virtual methods).
When you call ptr->sample(), you go to that table, find appropriate
function and give to this
function pointer to Base class as a parameter.
Dec 4 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4995
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class pointer which points to an instance of a derived class, but when I pass that base class pointer into a function, it can't access the derived object's public functions. Although, the base class pointer does call the appropriate virtual function...
9
4804
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
1
16240
by: ypjofficial | last post by:
Dear All, According to OOPs , a base class pointer can to point to derived class object....call this as fact1 But somehow I am not comfortable while understanding this concept. The explanaition to the fact1 is given as since the derived object always consists of the base part , the base class pointer will always point to the base part in the derived object unless otherwise the function in the base class are declared as virtual and are...
10
3330
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
2
2637
by: Jessica | last post by:
I have a base class and a derived class, but I am getting errors when I try to access functions of the derived class. Simplified version of my code is as follows: //////////////// // test2.hh class BaseClass {
3
1667
by: Randy | last post by:
Hi, I was learning about RTTI when I ran across this example. This line, out of the example, confused me. It is declaring a pointer to a base type and instantiating it with a derived class. I can say the words ... yet I don't get it. What do I have, a base or a derived? Can anyone push me in the right direction. abc *abc_pointer = new xyz();
15
3086
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I met with a strange issue that derived class function can not access base class's protected member. Do you know why? Here is the error message and code. error C2248: 'base::~base' : cannot access protected member declared in
10
3599
by: Dom Jackson | last post by:
I have a program which crashes when: 1 - I use static_cast to turn a base type pointer into a pointer to a derived type 2 - I use this new pointer to call a function in an object of the derived type 3 - this function then 'grows' the derived type object (by pushing onto a vector).
10
4112
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not allowed to access the protected data members of the base object. This surprises me. Can someone explain why this is? I suspect there is a good reason and I am just having a slow day to not come up with it myself. Bob
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.