Daniel Oliveira Daniel Oliveira - 1 month ago 17
C++ Question

C++ virtual class method

Imagine I have a super class A in C++ that has a virtual method. If I want to override it on my class B and still keep it virtual is it recommended to keep the virtual keyword on the class B on can I ignore it because I already said that method is virtual on the super class?

For example what is the correct way to do the following.

Method A:

class A{
public:
virtual void hello(){
std::cout << "Hello World!" << std::endl;
};
};
class B: public A{
public:
virtual void hello() override{
std::cout << "Hello Sun!" << std::endl;
};

};
class C: public B{
public:
virtual void hello() override{
std::cout << "Hello Moon!" << std::endl;
};

};


Or declaring the function as virtual only on the first class.

Method B:

class A{
public:
virtual void hello(){
std::cout << "Hello World!" << std::endl;
};
};
class B: public A{
public:
void hello() override{
std::cout << "Hello Sun!" << std::endl;
};

};
class C: public B{
public:
void hello() override{
std::cout << "Hello Moon!" << std::endl;
};

};


I want to use late biding in all situations. So I need the hello() method to be virtual in the three classes. Both ways worked on CodeBlocks but I don´t know what is the best way or even if there is any difference between them.

Answer

virtual is superfluous for B and C, and the effect is exactly the same. The important thing is to always mark your methods with override1 if they're meant to override a virtual method. While this is not strictly necessary, it is a good practice. You're doing that correctly in both examples.

Pertinent standardese:

n4140

§ 10.3 [class.virtual] / 2

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.


1 override as a specifier is available since C++11.