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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 May, 2022
Like Article
Save Article