Sign in to follow this  
Endar

Inheritance and base class pointers

Recommended Posts

Just before I go and re-write half my code when it might not even be necessary:
class A
{

}

class B : public A
{

}

class C : public B
{

}

The base pointer for class C is a pointer to an A object, isn't it? So, am I able to refer to an object of type C with a pointer to a B object. Or if I wanted to do that, would I have to do some casting?

Share this post


Link to post
Share on other sites
I'm not entirely sure what you are asking, but a C object pointer will have an implicit conversion to an A pointer or a B pointer.

Share this post


Link to post
Share on other sites

The following is allowed:

A a;
B b;
C c;

A* ap = &c;
ap = &b;
B* bp = &c;


If all your functions are virtual, you will call all functions from c after
ap = &c;

If there are some functions in A, which are not virtual or not defined in A.
You will need a cast:

static_cast<C*>(a)->someFunctionOfC(...);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this