A virtual function is a member function declared in a base class that is re-defined (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 execute the derived class’s version of the function.
Here we are not using any virtual functions.
#include <iostream>
using namespace std;
class A
{
int x=13;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 90;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
Value of x is : 13
*a is the base class pointer in the preceding example. The pointer can only access base class members and not derived class members. Although C++ allows the base pointer to point to any object derived from the base class, it cannot access the derived class’s members directly. As a result, a virtual function is required to allow the base pointer to access the members of the derived class.
Now let us see the same example but with the use of the virtual function.
#include <iostream>
using namespace std;
class A
{
int x=13;
public:
virtual void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 90;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
Value of y is : 90
Note: Using the virtual keyword, we can call the private function of a derived class from the base class pointer. Only at compile time does the compiler look for access specifiers. As a result, when late binding occurs at run time, it does not check whether we are calling a private or public function.
As we know if a class contains a virtual function, the compiler performs two actions.
Note: also read about Order of Constructor Call in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…