Visibility of members in inheritance

C

ctick

class A
{
public:
method_A() { cout << "A method " << endl; }
};

class B : public A
{
public:
method_B() { cout << "B method " << endl; }
};

int main()
{
A* aptr = new B;
....
}

Why cann't "aptr" see method_B() of class B since "aptr" is a pointer
pointing actually at an object of type B?

Thanks in advance!
 
V

Victor Bazarov

ctick said:
class A
{
public:
method_A() { cout << "A method " << endl; }

You mean

void method_A() { ...
};

class B : public A
{
public:
method_B() { cout << "B method " << endl; }

You mean

void method_B() { ...
};

int main()
{
A* aptr = new B;
...
}

Why cann't "aptr" see method_B() of class B since "aptr" is a pointer
pointing actually at an object of type B?

Because the _static_ type of aptr is A*. And it is not "pointing
actually" at a B, it is pointing to an A inside the B.

If you want to get to 'method_B', you will have to static_cast your
'aptr' to 'B*':

static_cast<B*>(aptr)->method_B();

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,171
Messages
2,570,935
Members
47,472
Latest member
KarissaBor

Latest Threads

Top