Can i override non virtual function in c++

Viewed 1080

i wanna know can i override non virtual function in c++ because i found this problem when playing with 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 display the following error
'B::say': method with override specifier 'override' did not override any base class methods but when i used virtual keyword in class A then error gone and code runs perfectly

3 Answers

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

No you cannot. "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."

Also see the answer here

override does not mean that the function you mark will magically override the base function. It's purpose is to tell the compiler "please check that I'm actually overriding a base class virtual function here and give me a nice compiler error if I screwed up, instead of doing something I did not intend".

If the base class function is virtual you don't need to say override, but you can do so to help yourself make fewer mistakes.

If the base class function is not virtual you cannot override it, override keyword or not.

Related