Can Virtual Functions be Private in C++?
Last Updated :
23 May, 2022
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.
Example:
C++
#include <iostream>
class base {
public :
base() { std::cout << "base class constructor\n" ; }
virtual ~base()
{
std::cout << "base class destructor\n" ;
}
void show()
{
std::cout << "show() called on base class\n" ;
}
virtual void print()
{
std::cout << "print() called on base class\n" ;
}
};
class derived : public base {
public :
derived()
: base()
{
std::cout << "derived class constructor\n" ;
}
virtual ~derived()
{
std::cout << "derived class destructor\n" ;
}
private :
virtual void print()
{
std::cout << "print() called on derived class\n" ;
}
};
int main()
{
std::cout << "printing with base class pointer\n" ;
base* b_ptr = new derived();
b_ptr->show();
b_ptr->print();
delete b_ptr;
}
|
Output
printing with base class pointer
base class constructor
derived class constructor
show() called on base class
print() called on derived class
derived class destructor
base class destructor
Explanation: ‘b_ptr‘ is a pointer of Base type and points to a Derived class object. When pointer ‘ptr->print()’ is called, function ‘print()’ of Derived is executed.
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...