The Wayback Machine - https://web.archive.org/web/20240921233910/https://www.geeksforgeeks.org/virtual-function-cpp/
Open In App

Virtual Function in C++

Last Updated : 06 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A virtual function (also known as virtual methods) is a member function that 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 method.

  • Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for the function call.
  • They are mainly used to achieve Runtime polymorphism.
  • Functions are declared with a virtual keyword in a base class.
  • The resolving of a function call is done at runtime.

Rules for Virtual Functions

The rules for the virtual functions in C++ are as follows:

  1. Virtual functions cannot be static.
  2. A virtual function can be a friend function of another class.
  3. Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime polymorphism.
  4. The prototype of virtual functions should be the same in the base as well as the derived class.
  5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
  6. A class may have a virtual destructor but it cannot have a virtual constructor.

Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions

Consider the following simple program showing the runtime behavior of virtual functions.

C++




// C++ program to illustrate
// concept of Virtual Functions
 
#include <iostream>
using namespace std;
 
class base {
public:
    virtual void print() { cout << "print base class\n"; }
 
    void show() { cout << "show base class\n"; }
};
 
class derived : public base {
public:
    void print() { cout << "print derived class\n"; }
 
    void show() { cout << "show derived class\n"; }
};
 
int main()
{
    base* bptr;
    derived d;
    bptr = &d;
 
    // Virtual function, binded at runtime
    bptr->print();
 
    // Non-virtual function, binded at compile time
    bptr->show();
 
    return 0;
}


Output

print derived class
show base class

Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of the base class type. Also, a base class pointer can point to the objects of the base class as well as to the objects of the derived class. In the above code, the base class pointer ‘bptr’ contains the address of object ‘d’ of the derived class.

Late binding (Runtime) is done in accordance with the content of the pointer (i.e. location pointed to by pointer) and Early binding (Compile-time) is done according to the type of pointer since the print() function is declared with the virtual keyword so it will be bound at runtime (output is print derived class as the pointer is pointing to object of derived class) and show() is non-virtual so it will be bound during compile time (output is show base class as the pointer is of base type).

Note: If we have created a virtual function in the base class and it is being overridden in the derived class then we don’t need a virtual keyword in the derived class, functions are automatically considered virtual functions in the derived class.

Working of Virtual Functions (concept of VTABLE and VPTR)

As discussed here, if a class contains a virtual function then the compiler itself does two things.

  1. If an object of that class is created then a virtual pointer (VPTR) is inserted as a data member of the class to point to the VTABLE of that class. For each new object created, a new virtual pointer is inserted as a data member of that class.
  2. Irrespective of whether the object is created or not, the class contains as a member a static array of function pointers called VTABLE. Cells of this table store the address of each virtual function contained in that class.

Consider the example below:
 

virtual pointer and virtual table

C++




// C++ program to illustrate
// working of Virtual Functions
#include <iostream>
using namespace std;
 
class base {
public:
    void fun_1() { cout << "base-1\n"; }
    virtual void fun_2() { cout << "base-2\n"; }
    virtual void fun_3() { cout << "base-3\n"; }
    virtual void fun_4() { cout << "base-4\n"; }
};
 
class derived : public base {
public:
    void fun_1() { cout << "derived-1\n"; }
    void fun_2() { cout << "derived-2\n"; }
    void fun_4(int x) { cout << "derived-4\n"; }
};
 
int main()
{
    base* p;
    derived obj1;
    p = &obj1;
 
    // Early binding because fun1() is non-virtual
    // in base
    p->fun_1();
 
    // Late binding (RTP)
    p->fun_2();
 
    // Late binding (RTP)
    p->fun_3();
 
    // Late binding (RTP)
    p->fun_4();
 
    // Early binding but this function call is
    // illegal (produces error) because pointer
    // is of base type and function is of
    // derived class
    // p->fun_4(5);
 
    return 0;
}


Output

base-1
derived-2
base-3
base-4

Explanation: Initially, we create a pointer of the type base class and initialize it with the address of the derived class object. When we create an object of the derived class, the compiler creates a pointer as a data member of the class containing the address of VTABLE of the derived class.

A similar concept of Late and Early Binding is used as in the above example. For the fun_1() function call, the base class version of the function is called, fun_2() is overridden in the derived class so the derived class version is called, fun_3() is not overridden in the derived class and is a virtual function so the base class version is called, similarly fun_4() is not overridden so base class version is called.

Note: fun_4(int) in the derived class is different from the virtual function fun_4() in the base class as prototypes of both functions are different.

Limitations of Virtual Functions

  • Slower: The function call takes slightly longer due to the virtual mechanism and makes it more difficult for the compiler to optimize because it does not know exactly which function is going to be called at compile time.
  • Difficult to Debug: In a complex system, virtual functions can make it a little more difficult to figure out where a function is being called from.


Previous Article
Next Article

Similar Reads

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 &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;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
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
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
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
C++ interview questions on virtual function and abstract class
1. What is a pure virtual function ? Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example. [GFGTABS] CPP // An abstract class class Test { // Data members of class publi
4 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
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 &amp; Work, Time and Distance, percentages, profit and loss, SI &amp; CI covered all major topics in aptitude)70 Technical (Digital, C basics &amp; Guessing the output, OS co
2 min read
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
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints "Base::show() called".
3 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 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
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
Pure Virtual Destructor in C++
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you m
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Virtual destruction using shared_ptr in C++
Prerequisite: shared_ptr, Virtual Destructor As we know, deleting a derived class object using a pointer to a base class that has non-virtual destructor results in undefined behavior. Thus, we make the base class destructor virtual so that the polymorphic objects are being deleted properly in the correct order (i.e. the reverse order of their creat
3 min read
Virtual base class in C++
Virtual base classes are used in virtual inheritance in a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritances.  Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is inherited by two other classes B and C. Both these class are inhe
3 min read
Can Virtual Functions be Private in C++?
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 [GFGTABS] C++ // C++ progr
4 min read
Advanced C++ | Virtual Constructor
In C++, we CANNOT make a constructor virtual. The reason is that C++ is a statically typed language, so the concept of a virtual constructor is a contradiction because the compiler needs to know the exact type at compile time to allocate the correct amount of memory and initialize the object correctly. If we attempt to make a constructor virtual, t
8 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include &lt;i
3 min read
wcscpy() function in C++ with Examples
The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination. Syntax: wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); Parameters: This method accepts the following two parameters: dest: specifies the pointer to the destination array. src: specifies the pointer
1 min read
wcscmp() function in C++ with Examples
The wcscmp() function is defined in cwchar.h header file. The wcscmp() function is used to compares two null terminating wide string and this comparison is done lexicographically. Syntax: int wcscmp(const wchar_t* str1, const wchar_t* str2); Parameters: This method takes the following two parameters: str1: This represents the pointer to the first s
2 min read
strtoul() function in C/C++
The strtoul() function in C/C++ which converts the initial part of the string in str to an unsigned long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. This function discard any white space characters until the first non-whitespace character is found, then takes as many characters as poss
3 min read
Practice Tags :