The Wayback Machine - https://web.archive.org/web/20240828113121/https://www.geeksforgeeks.org/difference-between-friend-function-and-virtual-function-in-cpp/
Open In App

Difference Between Friend Function and Virtual Function in C++

Last Updated : 12 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 


Similar Reads

Difference between friend function and member function in C++
Friend Function: It is basically a function that is used to access all private and protected members of classes. It is considered as a non-member function of class and is declared by the class that is granting access. This function is prefixed using the friend keyword in the declaration as shown below: Class definition using friend function: C/C++
4 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 Static and Friend Function in C++
Static Function: It is basically a member function that can be called even when the object of the class is not initialized. These functions are associated with any object and are used to maintain a single copy of the class member function across different objects of the class. This function is denoted by using the static keyword. Friend Function: I
3 min read
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
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Using Non-Member Friend Functions With Vector in C++ STL
In C++, Non-member buddy functions may access a class's private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods
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 Virtual Private Network (VPN) and Proxy
VPN: It stands for Virtual Private Network. It is a mechanism of employing encryption, authentication and integrity protection so that we can use public network as private network. It simulate a private network over public network. It allows users to remotely access a private network. Advantages of VPN: Security: VPN provides a high level of securi
4 min read
Difference between Virtual memory and Cache memory
Cache Memory: Cache memory increases the accessing speed of CPU. It is not a technique but a memory unit i.e a storage device. In cache memory, recently used data is copied. Whenever the program is ready to be executed, it is fetched from main memory and then copied to the cache memory. But, if its copy is already present in the cache memory then t
2 min read
Difference between Virtual Private Network (VPN) and Multi-Protocol Label Switching (MPLS)
Virtual Private Network (VPN): VPN is for virtual private networks, is a network type that is a private network but virtual. By applying VPN we can use public network as a private network as VPN is a tool of handling encryption, integrity protection and certification or authentication. It emulates a private network over a public network. This allow
4 min read
Difference between Chatbot and Virtual Assistant
1. Chatbot : Chatbot is a type of software that is programmed to interact with humans in such a way that it sounds like humans themselves. Chatbot is created using Natural Language Processing and Machine Learning. It identifies the meaning of the question asked by the user and collects data from the user that may be required to answer the question.
2 min read
Difference between Parallel Virtual Machine (PVM) and Message Passing Interface (MPI)
1. Parallel Virtual Machine (PVM) : PVM is a type of software tool which is designed for heterogeneous distributed computing. This software was created at the Oak Ridge National Laboratory in 1989 and it was rewritten in 1991 at the university of Tennessee. In this system, it allows a heterogeneous network which can be made from a collection of dis
2 min read
Difference between Virtual Machines and Containers
Virtual machines and Containers are two ways of deploying multiple, isolated services on a single platform. Virtual Machine:It runs on top of an emulating software called the hypervisor which sits between the hardware and the virtual machine. The hypervisor is the key to enabling virtualization. It manages the sharing of physical resources into vir
2 min read
Difference between Real and Virtual Images
Real and Virtual Images are the two types of images formed by the reflection and refraction of light rays. The key difference between real and virtual images is that the real image is formed by the actual intersection of light rays after reflection or refraction of light, while the virtual Images are formed when light rays appear to meet at a point
6 min read
Difference between Datagram Switching &amp; Virtual Circuit
1. Datagram switching : Datagram packet switching is a packet switching method that treats each packet, or datagram, as a separate entity. Each packet is routed via the network on its own. It is a service that does not require a connection. Because there is no specific channel for a connection session, there is no need to reserve resources. As a re
6 min read
Differences Between Virtual Circuits and Datagram Networks
Computer networks that provide connection-oriented services are called Virtual Circuits while those providing connection-less services are called Datagram networks. For prior knowledge, the Internet that we use is based on a Datagram network (connection-less) at the network level as all packets from a source to a destination do not follow the same
7 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 Function in C++
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 meth
6 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
Hot Standby Router Protocol (HSRP) and Virtual Router Redundancy Protocol (VRRP)
Hot Standby Router Protocol (HSRP) is a CISCO proprietary protocol used to provide redundancy in a network. Only one router is the active router while others will be in standby state i.e the standby router will be responsible for forwarding the traffic when the active router fails. Virtual Router Redundancy Protocol (VRRP) is an open standard proto
3 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
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
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
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
Kubernetes - Physical Servers vs Virtual Machines vs Containers
Kubernetes is an open-source framework for managing containerized workloads and services that allows declarative configuration as well as automation. It has a huge and fast-expanding ecosystem. Services, support, and tools for Kubernetes are widely available. Kubernetes is a Greek word that means "helmsman" or "pilot." The acronym K8s comes from co
3 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
Article Tags :
Practice Tags :