Search code examples
c++virtual-functions

compiler error on calling derived class function using base class pointer which is not in base class


I am learning C++ virtual functions.

#include<iostream>

class Base{
    virtual void fun(){
        std::cout<<"Base\n";
    }
};

class Derived:public Base{
    void fun(){
        std::cout<<"Derived\n";
    }
    virtual void fun1(){
        std::cout<<"Derived 1 \n";
    }
};

int main(){
    Base* b=new Derived();
    b->fun1();
}

I wrote this piece of code but it is not compiling. As per the concept of dynamic polymorphism, if we create a pointer of base class pointing to derived class, then we can call the functions of derived class, right?. Using virtual pointer of class Derived, we can call the fun1 function in virtual table, right?

But why it is not compiling here?


Solution

  • You can't call any Base or Derived member functions from outside the classes since the functions are private. You need to make them public

    The other problem: fun1 is not a member of Base so you can't call fun1 via a base class pointer.

    Two possible solutions:

    • Declare a pure virtual void fun1() = 0 in Base. Demo
    • Cast b to a Derived* before calling: static_cast<Derived*>(b)->fun1();. Demo

    Your program is also leaking memory. You need to delete b; and when you do it would now call the Base destructor only (with undefined behavior as a result) since your Base doesn't have a virtual destructor.

    virtual ~Base() = default;
    

    And then in main:

       // ...
       delete b;
    

    Demo using the smart pointer std::unique_ptr<Base> instead of having to delete manually.