I am learning C++ virtual functions. I declared a function as non virtual in base class, and same function as virtual in derived class. If i create base class pointer with derived object and call the function, it is calling base class function. How it is possible if that function is non virtual in base class?
#include<iostream>
using namespace std;
class Vehicle{
public:
void steer(){
cout<<"Steering Vehicle";
}
};
class Car: public Vehicle{
public:
virtual void steer(){
cout<<"Steering car";
}
};
int main(){
Vehicle* v1=new Car();
v1->steer();
return 0;
}
Current output
Steering Vehicle
Expected output
Steering car
Can someone help me understand why this is happening?
The current base class method
Vechicle::steer()is actually non-virtual. So the virtual method that you provided in the derived classCar::steer(), is not actually overrriding the base class method.To get your expected output, you can just mark the base class method
Vehicle::steer()to be virtual as shown below.Additionally, although not necessarily needed but you can mark the method in the derived class
overrideas also shown below:Working demo
Virtual functions should specify exactly one of virtual, override, or final