473,325 Members | 2,870 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,325 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 4887
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: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.