1

I know that when you want to declare a polymorphic function you have to declare the base class function virtual.

class Base
{
public:
    virtual void f();
};

My question is are you required to declare the inheriting class function as virtual, even if it's expected that Child behaves as if it were "sealed"?

class Child : public Base
{
public:
    void f();
};
1
  • I know if Child could be inherited from and f() in turn overridden virtual is required That is just plain wrong. because he base class's function is virtual, any inheriting function is implied virtual. As such, there is no need to use virtual again. Not ever. Commented Apr 20, 2012 at 20:42

3 Answers 3

7

No, you don't need to re-declare the function virtual.

A virtual function in a base class will automatically declare all overriding functions as virtual:

struct A
{
   void foo();          //not virtual
};
struct B : A
{
   virtual void foo();  //virtual
}
struct C : B
{
   void foo();          //virtual
}
Sign up to request clarification or add additional context in comments.

1 Comment

remember to re-edit your example so that C is inheriting from B.
0

Declaring f() as virtual in Child helps some one reading the definition of Child. It is useful as documentation.

Comments

0

Once the base class override is marked as virtual all other overrides are implicitly so. While you are not required to mark the function as virtual I tend to do so for documentation purposes.

As of the last part: even if it's expected that Child behaves as if it were "sealed"?, if you want to seal the class, you can actually do it in C++11 (this was not fully implementable in C++03 generically) by creating a seal class like so:

template <typename T>
class seal {
   seal() {}
   friend T;
};

And then inheriting your sealed class from it (CRTP):

class Child : public Base, virtual seal<Child> {
// ...
};

The trick is that because of the use of virtual inheritance, the most derived type in the hierarchy must call the virtual base constructor (int this case seal<Child>), but that constructor is private in the templated class, and only available to Child through the friend declaration.

In C++ you would have to either create a seal type for every class that you wanted to seal, or else use a generic approach that did not provide a perfect seal (it could be tampered with)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.