devxlogo

When to Declare a Virtual Member Function Private

When to Declare a Virtual Member Function Private

Declaring a virtual member function private may be useful when you wish to limit the number of derived classes that can override the given function. In such a case, you declare all the derived classes, which will be able to override the private virtual member function as friends of the base class.
In the following example, only B can override the member function f().

 class A {  friend class B;private:  virtual int f() { return 1; }};class B : public A {private:  virtual int f() { return 2; }};class C : public A { // will use A::f(), cannot _override it};class D : public B { // will use B::f(), cannot _override it};

devx-admin

Share the Post: