473,231 Members | 1,786 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

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::sample\n");
};
};

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

int main()
{
Derived1 *ptr = reinterpret_cast<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 4884
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("derived::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cast<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_cast' 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.********@comAcast.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("derived::sample\n");
};
};

int main()
{
Derived1 *ptr = reinterpret_cast<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_cast' 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_cast 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...@comAcast.netwrote:
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("derived::sample\n");
};
};
int main()
{
Derived1 *ptr = reinterpret_cast<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_cast' 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...@comAcast.netwrote:
>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("derived::sample\n");
};
};
>>int main()
{
Derived1 *ptr = reinterpret_cast<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_cast' 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::sample\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::sample\n");
};
};

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

int main()
{
Derived1 *ptr = reinterpret_cast<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
Hey, guys!

I want to know waht do you think about my assumptions.Are they correct?
Dec 5 '07 #11
yurec wrote:
I want to know waht do you think about my assumptions.Are they
correct?
At least one of them isn't: you assume we remember what you
posted about.

If you want to ask a follow-up question, quote enough of the
original discussion so at least some context is retained.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 5 '07 #12
On Dec 5, 4:23 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
yurec wrote:
I want to know waht do you think about my assumptions.Are they
correct?

At least one of them isn't: you assume we remember what you
posted about.

If you want to ask a follow-up question, quote enough of the
original discussion so at least some context is retained.

V
--
On Dec 4, 10:09 am, yurec <Yurij.Zha...@materialise.kiev.uawrote:
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::sample\n");
};
};
class Derived1: public Base1
{
public: void sample()
{
printf("derived::sample\n");
};
};
int main()
{
Derived1 *ptr = reinterpret_cast<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.- Hide quoted text -

- Show quoted text -
Dec 5 '07 #13
>yurec wrote:
>>I want to know waht do you think about my assumptions.Are they
correct?

[..]
In first case (with virtual method) both classes have pointer to
virtual method table.
That's something that is not defined by the language. You are free
to assume that, of course, but then you're in implementation-specific
area.
>With reinterpret_cst you say to compiler to work with Base, as it has
memory layout as Derived class.
....about which the Standard explicitly says that the result of such
conversion is unspecified ([expr.reinterpret.cast]/7).
>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.- Hide quoted text -
Going into how things are implemented... The "special table" only
exists during compilation/linking. After the program has been
built, there is no "special table for Derived methods". All calls
have been statically resolved to fixed addresses in memore (for
non-inlined calls) or inlined.

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

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

Similar topics

9
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...
9
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...
1
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...
10
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
2
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...
3
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...
15
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:...
10
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...
10
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...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.