"scott" <sc***********@hotmail.com> wrote in message
news:ck**********@newsg2.svr.pol.co.uk...
Lets say i have class A class B and class C.
Class C inherites class B and class B inherites class A. Class A contains
a
vertual function (not pure) and class C contains the same vertual
function.
In my code i get the address of class A (i can't get the address of the
other classes, its children) and then call the vertual function. It then
in
turn calls the vertual function of class C. Is there any way of getting
the
address of class C, c++ seems to have done it some how cos it called the
function in class C instaed of class A.
Well not exactly. The way virtual functions are usually implemented is that
each object carries around a pointer to a table of function pointers. Your C
object is carrying a pointer to a table of C function pointers. So when you
call a virtual function using an A pointer it still calls the C function
because it looks up, at run time, the function to call in the table.
Thx for any help
Scott
What you are asking to do is called a downcast. You want to go from A* to
C*, which is down the inheritance hierarchy.
Obviously this is dangerous because you cannot be sure that your A* variable
is really pointing to a C object. But if you are really, really sure then
you can simply to a static_cast
A* ptr = ...;
C* ptr2 = static_cast<C*>(ptr);
If you are wrong this will most likely crash your program.
If you aren't really sure then you can do a dynamic_cast
A* ptr = ...;
C* ptr2 = dynamic_cast<C*>(ptr);
if (ptr2 != NULL)
{
...
The difference is that if ptr wasn't pointing to a C object then dynamic
cast will return NULL.
I don't know why you want to do this, but normally it is better to add more
virtual functions to your classes than to try downcasting. Often when you
think you need to downcast what it really means is that you need to think a
harder about how your classes are designed.
john