Search code examples
c++overriding

Can I override a non-virtual function in C++?


I want to know if I can override a non-virtual function in C++. I found this problem when playing with the C++ override keyword. I have the code as follows :

class A
{
public:
    void say()
    {
        cout << "From A\n";
    }
};
class B : public A {
public:
    void say()
        override
    {
        cout << "From B\n";
    }
};

But when I execute the code, Visual Studio displays the following error:

'B::say': method with override specifier 'override' did not override any base class methods

But when I use the virtual keyword in class A, the error is gone and the code runs perfectly.


Solution

  • You do not override say in B

    from C++ override specifier :

    In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from a base class. The program is ill-formed (a compile-time error is generated) if this is not true.

    Look at that example :

    #include <iostream>
    
    class A
    {
      public:
        void say()
        {
            std::cout << "From A\n";
        }
    };
    
    class B : public A {
      public:
        void say()
            //override
        {
            std::cout << "From B\n";
        }
    };
    
    int main()
    {
      A a;
      B b;
      
      a.say();
      b.say();
      ((A &) b).say();
    }
    

    Compilation and execution :

    pi@raspberrypi:/tmp $ g++ c.cc
    pi@raspberrypi:/tmp $ ./a.out
    From A
    From B
    From A
    pi@raspberrypi:/tmp $ 
    

    Putting say virtual in A (so implicitely in B) ((A &) b).say(); prints From B because that time there is overriding