Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C++ virtual definition inherited automatically?

Is C++ virtual definition recursive? Consider

class Foo
     {
     public:
          virtual void a()=0;
     };

class Bar:public Foo
     {
     public:
         void a()
             {
         //...
             }
     };

If I now inherit Bar and overload a again, is that a also polymorphic?

Recursive means that

Given a class A that has a virtual member a, and a virtual member of the n:th subclass of A, then a is also a virtual member of the n+1:th subclass, for all n.

That is, virtual functions follow Peanos induction axiom and is not terminated after one level.

like image 709
user877329 Avatar asked Dec 09 '22 03:12

user877329


1 Answers

If you inherit from Bar you should have

class Bar:public Foo
     {
     public:
         virtual void a() override
             {
         //...
             }
     };

So you are saying two things about a() here:

  1. The function is virtual so anything that derives from Bar will treat the function as virtual
  2. You are overriding the function a from the base class Foo

As @MikeSeymour and @Bathsheba mentioned, the virtual keyword in Bar is superfluous as the function will be treated as virtual since it was in the base class. However, I tend to be in the habit of using virtual/override as shown in my example so it is immediately clear how this function is to be used at first glance of the class without having to walk up the inheritance.

like image 106
Cory Kramer Avatar answered Dec 22 '22 01:12

Cory Kramer