Is the C ++ virtual definition automatically inherited?

Is C ++ a virtual definition recursive? Consider

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

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

If I now inherit Barand overload aagain, is that aalso polymorphic?

Recursive means that

Given a class athat has a virtual member aand a virtual member n: th of a subclass a, then ait is also a virtual member of the n+1th subclass, for all n.

That is, virtual functions follow the axiom of Pianos induction and do not interrupt after one level.

+4
source share
4 answers

If you inherit from Bar, you must have

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

, a() :

  • , , Bar,
  • a Foo

@MikeSeymour @Bathsheba, virtual Bar virtual, . , , virtual/override, , , .

+4

"" - ; , , , .

+4

(i) , (ii) (iii) , virtual , .

, , void bar::a() . , virtual -ness .

. , . - . - .

+4

In the normal case, an overridden virtual function in itself is virtual. It doesn't matter if the function of the parent class was virtual because you used the keyword virtualor because its own parent was virtual.

Beware when you "hide" one function with a different name, but with a different signature. This feature is not virtual!

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

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

class Baz1 : public Bar
     {
     public:
         void a(); // also virtual
     };

class Baz2 : public Bar
     {
     public:
         void a(int); // not virtual!
     };
+2
source

All Articles