Cannot call function of derived class using base class pointers

I want to call a function of a derived class that is not defined in the base class using pointers to the base class. but this always causes an error:

error C2039: 'derivedFunctionName' : is not a member of 'BaseClass' 

Do you know how I could get around this?

Thanks,

+4
source share
3 answers

You cannot call an element that appears only in a derived class with a pointer to the base class; you should use it (possibly using dynamic_cast ) for a pointer to a derived type, firstly - otherwise the compiler has no idea that the method exists.

It might look something like this:

 void someMethod(Base* bp) { Derived *dp = dynamic_cast<Derived*>(bp); if (dp != null) dp->methodInDerivedClass(); } 
+13
source

One way is to make the virtual function in the base class and then override it in the derived class. You do not need to define a function in the base class (although you can), but you can use pure virtual syntax in the base class virtual void foo() = 0; if you do not want to provide an implementation in the base class.

This will allow you to override it in the derived class and still call it in the base class using the base class pointer. This is known as polymorphism.

You can also just pass it to the derived type at run time if you are sure that it is actually a pointer to the derived class at that time. If it is not, it will work.

+5
source

You can call an element of a derived class through a pointer to the base class, if this method is virtual. What is polymorphism.

For this to work, you must declare a virtual method (possibly a pure virtual) in the base class and overload it in the derived class.

Please note that you will encounter problems causing the derived element from the base method. Make some notes of ARM or Meyers if that doesn't make sense to you.

+2
source

Source: https://habr.com/ru/post/1490147/


All Articles