The Wayback Machine - https://web.archive.org/web/20241127233116/https://www.geeksforgeeks.org/can-virtual-functions-be-private-in-c/
Open In App

Can Virtual Functions be Private in C++?

Last Updated : 24 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 1: Calling Private Virtual Function from Base Class Pointer to Derived Class Instance

C++
// C++ program to demonstrate how a
// virtual function can be private
#include <iostream>

using namespace std;

class base {
public:
    // default base constructor
    base() { cout << "base class constructor\n"; }

    // virtual base destructor
    // always use virtual base
    // destructors when you know you
    // will inherit this class
    virtual ~base() { cout << "base class destructor\n"; }
    // public method in base class
    void show() { cout << "show() called on base class\n"; }

    // public virtual function in base class,
    // contents of this function are printed when called
    // with base class object when called with base class
    // pointer contents of derived class are printed on
    // screen
    virtual void print()
    {
        cout << "print() called on base class\n";
    }
};

class derived : public base {
public:
    // default derived constructor
    derived()
        : base()
    {
        cout << "derived class constructor\n";
    }
    // virtual derived destructor
    // always use virtual destructors
    // when inheriting from a
    // base class
    virtual ~derived()
    {
        cout << "derived class destructor\n";
    }

private:
    // private virtual function in derived class overwrites
    // base class virtual method contents of this function
    // are printed when called with base class pointer or
    // when called with derived class object
    virtual void print()
    {
        cout << "print() called on derived class\n";
    }
};

int main()
{
    cout << "printing with base class pointer\n";

    // construct base class pointer with derived class
    // memory
    base* b_ptr = new derived();

    // call base class show()
    b_ptr->show();

    // call virtual print in base class but it is overridden
    // in derived class also note that print() is private
    // member in derived class, still the contents of
    // derived class are printed this code works because
    // base class defines a public interface and drived
    // class overrides it in its implementation
    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.

Example 2: Calling Private Virtual Function from within Derived Class

C++
#include <iostream>

using namespace std;

// Base class declaration
class Base {
public:
    Base() {}
    virtual ~Base() {}

    // Public method that calls the private virtual function
    void show() { printMe(); }

private:
    // Private virtual function that can be overridden in
    // derived classes
    virtual void printMe()
    {
        cout << "Base calling printMe!!!\n";
    }
};

// Derived class inheriting from Base class
class Derived : public Base {
public:
    Derived(){}
    virtual ~Derived() {}

private:
    // Override the private virtual function in the derived
    // class
    virtual void printMe() override
    {
        cout << "Derived calling printMe!!!!\n";
    }
};

int main()
{
    Derived dd;
    dd.show();
    return 0;
}

Output
Derived calling printMe!!!!

Explanation

Base Class:

  • The Base class has a public method show which calls a private virtual function printMe.
  • The printMe function is declared as private and virtual, allowing it to be overridden in derived classes.

Derived Class:

  • The Derived class inherits from Base and overrides the printMe function.

main Function:

  • An instance of the Derived class is created.
  • The show method of the Derived instance is called.

We then call the printMe method, but since it is overridden in the Derived class, the derived class implementation is executed, printing “Derived calling printMe!!!!” even though it is private in the Base class.




Previous Article
Next Article

Similar Reads

Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location with the definition of the inline function at compil
2 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Can a constructor be private in C++ ?
Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ? Answer : Ye
3 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
C++ | Virtual Functions | Question 1
Which of the following is true about virtual functions in C++. (A) Virtual functions are functions that can be overridden in derived class with the same signature. (B) Virtual functions enable run-time polymorphism in a inheritance hierarchy. (C) If a function is 'virtual' in the base class, the most-derived class's implementation of the function i
1 min read
C++ | Virtual Functions | Question 2
Predict output of the following program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->show(); Base &br = *bp; br.show(
1 min read
C++ | Virtual Functions | Question 3
Output of following program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp, b; Derived d; bp = &d; bp->show(); bp = &b; bp->show();
1 min read
C++ | Virtual Functions | Question 5
#include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; int main(void) { Base b; Base *bp; return 0; } (A) There are compiler errors in lines "Base b;" and "Base bp;" (B) There is compiler error in line "Base b;" (C) There is compiler error in line "Base bp;" (D) No compiler Error Answer: (B) Explanation: Sinc
1 min read
C++ | Virtual Functions | Question 6
Predict the output of following program. #include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived : public Base { }; int main(void) { Derived q; return 0; } (A) Compiler Error: there cannot be an empty derived class (B) Compiler Error: Derived is abstract (C) No compiler Error Answer: (B) Explanat
1 min read
C++ | Virtual Functions | Question 7
#include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Derived d; Base &br = d; br.show(); return 0; } (A) Compiler Error in line "Base &br = d;" (B) Empty Output (C) In Derived Answer: (C)
1 min read
C++ | Virtual Functions | Question 14
Can a constructor be virtual? Will the following program compile? #include <iostream> using namespace std; class Base { public: virtual Base() {} }; int main() { return 0; } (A) Yes (B) No Answer: (B) Explanation: There is nothing like Virtual Constructor. Making constructors virtual doesn't make sense as constructor is responsible for creati
1 min read
C++ | Virtual Functions | Question 9
Can a destructor be virtual? Will the following program compile? #include <iostream> using namespace std; class Base { public: virtual ~Base() {} }; int main() { return 0; } (A) Yes (B) No Answer: (A) Explanation: A destructor can be virtual. We may want to call appropriate destructor when a base class pointer points to a derived class object
1 min read
C++ | Virtual Functions | Question 10
#include<iostream> using namespace std; class Base { public: Base() { cout<<"Constructor: Base"<<endl; } virtual ~Base() { cout<<"Destructor : Base"<<endl; } }; class Derived: public Base { public: Derived() { cout<<"Constructor: Derived"<<endl; } ~Derived() { cout<<
1 min read
C++ | Virtual Functions | Question 11
Can static functions be virtual? Will the following program compile? #include<iostream>  using namespace std;      class Test {    public:       virtual static void fun()  { } }; (A) Yes (B) No Answer: (B) Explanation: Static functions are class specific and may not be called on objects. Virtual functions are called according to the pointed o
1 min read
C++ | Virtual Functions | Question 12
Predict the output of following C++ program. Assume that there is no alignment and a typical implementation of virtual functions is done by the compiler. #include <iostream> using namespace std; class A { public: virtual void fun(); }; class B { public: void fun(); }; int main() { int a = sizeof(A), b = sizeof(B); if (a == b) cout <<
1 min read
C++ | Virtual Functions | Question 13
#include <iostream> using namespace std; class A { public: virtual void fun() { cout << "A::fun() "; } }; class B: public A { public: void fun() { cout << "B::fun() "; } }; class C: public B { public: void fun() { cout << "C::fun() "; } }; int main() { B *bp = new C; bp->fun(); return 0; } (A
1 min read
C++ | Virtual Functions | Question 14
Predict the output of following C++ program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->Base::show(); // Note the use of
1 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Publicly inherit a base class but making some of public method as private
There are certain situation when we want to make some of the public base class functions as private in the derived class. Suppose both base and child class has getter and setter methods // CPP program to demonstrate that all base // class public functions become available // in derived class if we use public inheritance. #include <iostream> u
3 min read
Private Destructor in C++
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private. What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private. For dynamically created objects, it
4 min read
Difference between Private and Protected in C++ with Example
Protected Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example: [GFGTABS] CPP // C++ program to demonstrate // protected access modifier #include &lt;
3 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Target Corporation Interview Experience | On-Campus Virtual Hiring
Round 1 - Online test This round has MCQ s regrading English reading comprehension, Reasoning, logical, Quantitative(Numerical) and technical questions. Technical questions were related to computer science domain. This round also has 2 coding questions: Counting the duplicate elements in an arrayOptimal oil flow problem Both questions had 2 public
3 min read
ARM Interview Experience for Intern (On-Campus Virtual 2020)
ARM talent acquisition team visited our campus virtually for an intern role in the verification domain. There were totally 3 rounds, Round 1 (Written Test) : 30 Aptitude (Time & Work, Time and Distance, percentages, profit and loss, SI & CI covered all major topics in aptitude)70 Technical (Digital, C basics & Guessing the output, OS co
2 min read
Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
Practice Tags :
three90RightbarBannerImg