Base class pointer calling non virtual base function which is virtual in derived class

84 views Asked by At

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?

1

There are 1 answers

0
user12002570 On

The current base class method Vechicle::steer() is actually non-virtual. So the virtual method that you provided in the derived class Car::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 override as also shown below:

class Vehicle{
        public:
//------vvvvvvv----------------->added this virtual keyword to make this virtual 
        virtual void steer(){
                cout<<"Steering Vehicle";
        }
};
class Car: public Vehicle{
        public:
//------v------------------------->not necessary to use virtual and override keyword here 
        void steer() override     
        {
                cout<<"Steering car";
        }
};

Working demo


Virtual functions should specify exactly one of virtual, override, or final