Open In App

Difference Between Friend Function and Virtual Function in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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 include object/s as arguments. It is mostly used for overloading <<and>> for I/O. It can generally access any member of the class to which it is friend.  

Illustration: 

class GFG  
{ 
 private: 
 {  
 Public: 
 {  
 friend void check();  
 }
  
void check();  

Now coming onto the second function is a virtual function. So a virtual function is basically a member function of a class that is declared within the base class. In this, a virtual keyword is used to make member function of base class Virtual. It also supports polymorphism at both compile-time and run time. It also allows derived class to simply replace implementation that is provided or given by the base class.  

Illustration:  

class GFG  
{  
Public:  
          Virtual return_type function_name(arguments)  
         {  
         …..  
         }  
}:  
   class A  
  {  

By far we are clear with discussing friend function and virtual function, now let us see the major differences between them even to grasp a good grip over it.

Friend Function 

Virtual Function 

It is non-member functions that usually have private access to class representation.   It is a base class function that can be overridden by a derived class.  
It is used to access private and protected classes.  It is used to ensure that the correct function is called for an object no matter what expression is used to make a function class.
It is declared outside the class scope. It is declared using the ‘friend’ keyword. It is declared within the base class and is usually redefined by a derived class. It is declared using a ‘virtual‘ keyword.
It is generally used to give non-member function access to hidden members of a class.   It is generally required to tell the compiler to execute dynamic linkage of late binding on function.  
They support sharing information of class that was previously hidden, provides method of escaping data hiding restrictions of C++, can access members without inheriting class, etc.   They support object-oriented programming, ensures that function is overridden, can be friend of other function, etc.  
It can access private members of the class even while not being a member of that class.   It is used so that polymorphism can work. 

Last Updated : 12 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads