C Programming and Data Structures (16 Blogs)

How To Implement Virtual Function in C++?

Published on Aug 07,2019 18.6K Views

How To Implement Virtual Function in C++?

A virtual function in C++ is a member function within the base class that we redefine in a derived class. This article will help you explore the concept in detail. Following Pointers will be covered in this article,

So let us get started with this article on Virtual Function in C++

What is Virtual Function?

A virtual function is a member function within the base class that we redefine in a derived class. It is declared using the virtual keyword. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.

Moving on with this article on Virtual Function in C++

Rules for Virtual Function in C++:

  • They are always defined in a base class and overridden in derived class but it is not mandatory to override in the derived class.
  • The virtual functions must be declared in the public section of the class.
  • They cannot be static or friend function also cannot be the virtual function of another class.
  • The virtual functions should be accessed using a pointer to achieve run time polymorphism.

Moving on with this article on Virtual Function in C++.

What is binding?

Binding for functions means that wherever there is a function call, the compiler needs to know which function definition should it be matched to. This depends upon the signature of each function declaration & the assignments that are taken. Also, the compiler needs to know that when this matching between the function call and choosing the correct definition will happen.

Moving on with this article on Virtual Function in C++

Early Binding

Early binding is a phenomenon wherein the decision to match various function calls happens at the compile time itself and the compiler directly associates the link with addresses. It is also known as Static Binding or Compile-time Binding.

  • As we know we write code in the high-level language
  • Then the compiler converts this into low-level language that computer can understand, mostly machine language at the time of compilation
  • In early binding, the compiler directly provides the address of function declaration instruction to the function call instruction
  • Thus as the name suggests the binding happens very early before the program runs.

Example

#include <iostream>
using namespace std;
class Animals
{
public:
void sound()
{
cout << "Genric animal sound" << endl;
}
};
class Cats: public Animals
{
public:
void sound()
{
cout << "Cat meow" << endl; } }; int main() { Animals *a; Cats c; a= &c; a -> sound();   //  early binding
return 0;
}

Output

Output- Virtual function in C++- Edureka

Explanation
In this example, we created a pointer a to the parent class Animals. Then by writing a= &c, the pointer ‘a’ started referring to the object c of the class Cats.
a -> sound(); – On calling the function sound() which is present in both the classes by the pointer ‘a’, the function of the parent class got called, even if the pointer is referring to the object of the class Cats.

This is due to Early Binding. We know that ‘a’ is a pointer of the parent class referring to the object of the child class. Since early binding takes place at compile-time, therefore when the compiler saw that ‘a’ is a pointer of the parent class, it matched the call with the ‘sound()’ function of the parent class without searching for object the pointer it is referring to.

Moving on with this article on Virtual Function in C++

Late Binding

In late binding, the compiler identifies the object at runtime and then matches the function call with the correct function. It is also known as Dynamic Binding or Runtime Binding.

Late binding in the above problem may be solved by using virtual keyword in the base class. Let’s see how this happens by using the above example itself, but only adding virtual keyword.

Example

#include <iostream>
using namespace std;
class Animals
{public:
virtual void sound()
{
cout << "Genric aniaml sound" << endl;
}
};
class Cats: public Animals
{
public:
void sound()
{
cout << "Cats meow" << endl; } }; int main() { Animals *a; Cats c; a= &c; a -> sound();
return 0;
}

Output

Output- Virtual function in C++- Edureka

Explanation
Here the function sound() of the base class is made virtual, thus the compiler now performs late binding for this function. Now, the function call of the sound() function will be matched to the function definition at runtime. Since the compiler now identifies pointer ‘a’ as referring to the object ‘c’ of the derived class Cats, it will call the sound() function of the class Cats.

Moving on with this article on Virtual Function in C++

Pure Virtual Function

A pure virtual function in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.

virtual void sound() = 0;

Here sound() is a pure virtual fuction.

Moving on with this article on Virtual Function in C++

Abstract Class

An abstract class is defined as a class with one or more pure virtual functions. As explained above pure virtual function is a virtual member function that is marked as having no implementation. It has no implementation possible with the information provided in the class, including any base classes. An abstract class is also known as an abstract base class.

Example

#include <iostream>
using namespace std;
class Employee  //  abstract base class
{
virtual int getSalary() = 0;  // pure virtual function
};
class Employee_1: public Employee
{
int salary;
public:
Employee_1(int s)
{
salary = s;
}
int getSalary()
{
return salary;
}
};
class Employee_2: public Employee
{
int salary;
public:
Employee_2(int t)
{
salary = t;
}
int getSalary()
{
return salary;
}
};
int main()
{
Employee_1 e1(5000);
Employee_2 e2(3000);
int a, b;
a = e1.getSalary();
b = e2.getSalary();
cout << "Salary of Developer : " << a << endl;
cout << "Salary of Driver : " << b << endl;
return 0;
}

Output

Output- Virtual function in C++- Edureka

Explanation
The ‘getSalary()’ function in the class Employee is a pure virtual function. Since the Employee class contains the pure virtual function, therefore it is an abstract base class.
Since the pure virtual function is defined in the subclasses, therefore the function ‘getSalary()’ is defined in both the subclasses of the class Employee i.e in Employee_1 and Employee_2.

Moving on with this article on Virtual Function in C++

Example for Virtual Function

#include<iostream>
using namespace std;
class base
{
public:
void function_1() { cout << "base class function 1n"; }
virtual void function_2() { cout << "base class function 2n"; }
virtual void function_3() { cout << "base class function 3n"; }
virtual void function_4() { cout << "base class function 4n"; }
};
class derived : public base
{
public:
void function_1() { cout << "derived class function 1n"; }
void function_2() { cout << "derived class function 2n"; }
void function_4(int x) { cout << "derived class function 4n"; } }; int main() { base *ptr; derived obj1; ptr = &obj1; ptr->function_1();
ptr->function_2();
ptr->function_3();
ptr->function_4();
}

Output

Output- Virtual function in C++- Edureka

Explanation
For function_1() function call, base class version of function is called, function_2() is overridden in derived class so derived class version is called, function_3() is not overridden in derived class and is virtual function so base class version is called, similarly function_4() is not overridden so base class version is called.

Thus we have come to an end of this article on ‘Virtual Function in C++’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Implement Virtual Function in C++?

edureka.co