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};
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist