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?
fun1()
function in theBase
class. Second, yourBase
class lacks a virtual destructor, thus if you were to attempt to issue adelete b;
, you are invoking undefined behavior. – PaulMcKenzieDerived
forBase
for howeverBase
is used.Base
has nofun1
, there's nothing to ever try to substitute. – StoryTeller - Unslander Monica