1
votes

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?

1
That's not how polymorphism works. I see no fun1() function in the Base class. Second, your Base class lacks a virtual destructor, thus if you were to attempt to issue a delete b;, you are invoking undefined behavior.PaulMcKenzie
polymorphism is about substituting one type for another. I.e., being able to substitute Derived for Base for however Base is used. Base has no fun1, there's nothing to ever try to substitute.StoryTeller - Unslander Monica

1 Answers

3
votes

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.