Sign in to follow this  

Inheritance and base class pointers

This topic is 4513 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

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

This topic is 4513 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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