Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to call derived class function using base class pointers

Tags:

c++

I want to call a derived class function that isn't defined in the base class using base class pointers. but this always raises the error:

error C2039: ‘derivedFunctionName’ : is not a member of ‘BaseClass’

Do you know how I could get around this?

Thanks,

like image 835
Sujeeth Damodharan Avatar asked Jul 07 '13 17:07

Sujeeth Damodharan


People also ask

Can a base class pointer access derived class function?

Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.

Is derived class pointer Cannot point to base class?

The actual reason is - a derived class has all information about a base class and also some extra bit of information. Now a pointer to a derived class will require more space and that is not sufficient in base class. So the a pointer to a derived class cannot point to it.

Why can't a derived pointer reference a base object?

similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.

Can we call base class method using derived class object?

Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.


1 Answers

You can't call a member that appears only in a derived class through a pointer to the base class; you have to cast it (probably using dynamic_cast) to a pointer to the derived type, first -- otherwise the compiler has no idea the method even exists.

It might look something like this:

void someMethod(Base* bp) {
    Derived *dp = dynamic_cast<Derived*>(bp);
    if (dp != null)
        dp->methodInDerivedClass();
}
like image 146
Ernest Friedman-Hill Avatar answered Sep 27 '22 18:09

Ernest Friedman-Hill