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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…