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?
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:
virtual void fun1() = 0
in Base
. Demob
to a Derived*
before calling: static_cast<Derived*>(b)->fun1();
. DemoYour 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.