Can Virtual Functions be Private in C++?
Virtual functions can be overridden by derived classes but, under any circumstances, will only be called within the base class. Therefore you can make a virtual function private as C++ has access control but no visibility control.
Let us be clear about it through an example:
#include<iostream>
using namespace std;
class Derived;
class Base {
private:
virtual void function() { cout << "Base Function"; }
friend int main();
};
class Derived: public Base {
public:
void function() { cout << "Successful"; }
};
int main()
{
Base *pointer = new Derived;
pointer->function();
return 0;
}
Output
Successful
The above program gets compiled successfully and runs fine. Thus it is proved that virtual functions can be private.
Explanation
pointer is a pointer of Base type and points to a Derived class object. When pointer->function() is called, function() of Derived is executed. int main() is a friend of Base, i.e., the base class defines a public interface. If we remove this friendship, the program won't compile. This code works because the base class defines a public interface, and the derived class overrides it in its implementation even though the derived has a private virtual function. In Java, this behavior is totally different; private methods are final by default and cannot be overridden.
Frequently Asked Questions
What is a virtual function?
A member function declared within a base class and overridden by a derived class is called a virtual function.
Can virtual functions be private?
Virtual functions can be overridden by derived classes but, under any circumstances, will only be called within the base class. Therefore you can make a virtual function private as C++ has access control but no visibility control.
Do virtual functions have to be public?
Virtual functions can have public , protected , or private access.
Conclusion
In this article, we have extensively discussed virtual functions and if virtual functions can be private through an example and explanation. Having gone through this article, I am sure you must be excited to read similar blogs. Coding Ninjas has got you covered. Here are some similar blogs to redirect: What is virtual function?, Introduction to virtual functions, Virtual function and runtime polymorphism and Difference between default and pure virtual functions We hope that this blog has helped you enhance your knowledge, and if you wish to learn more, check out our Coding Ninjas Blog site and visit our Library. Do upvote our blog to help other ninjas grow.
Happy Learning!