Reputation: 1
I cannot find the answer, so maybe someone will be able to help me. I don't understand why I can't call ptr->other(). THX
class A
{
public:
A(){}
virtual ~A(){}
virtual void fun(){ cout<<"fun A"<<endl;}
};
class B: public A
{
public:
B(){}
~B(){}
virtual void fun(){ cout<<"fun B"<<endl;}
void other(){cout<<"other fuction"<<endl;}
};
int main()
{
A *ptr = new B();
ptr->fun();
ptr->other(); //it doesn't work :(
}
Upvotes: 0
Views: 139
Reputation: 5166
Use have to implicitly tell that the ptr belongs to an object B since ptr used a B constructor :
((B*)(ptr))->other();
Upvotes: 0
Reputation: 148910
That is not the way polymorphism is supposed to be used.
You can indeed assign a B*
to a A*
, but all the time that you use a pointer to A
, you can only use members belonging to A
.
If you have a pointer to A
and need to use a member of B
, you must first downcast the pointer. You can use a static_cast
is you know that the pointer does point to a B
object, or a dynamic_cast
if you want to have a chance to control that:
B* pb = static_cast<B *>(ptr); // unconditional cast
pb->other(); // undefined behaviour if ptr does not point to a B object
but
B* pb = dynamic_cast<B *>(ptr); // pb will be null if ptr does not point to a B object
if (pb != nullptr) pb->other(); // perfectly defined behaviour
Upvotes: 3
Reputation: 12227
It's not suppose to work because other()
is not defined in A.
In your example the function fun()
is correct way of using polymorphism, it needs to be defined in base class and overridden in derived class. It is not the case with other()
function.
Upvotes: 1
Reputation: 5554
C++ is statically typed, and ptr
is an A *
. When you call ptr->fun
, the compiler sees that A
has a virtual fun
and uses what's called a virtual function table to find B::fun
at run time. When you call ptr->other
, the compiler sees that A
has no other
at all, so that's an error. That's why you have to use a static_cast
to tell the compiler to look in B
first.
Upvotes: 0