Difference Between Friend Function And Virtual Function In C++ - C++ Programming Tutorial
C++ Course / C++ vs Other Languages / Difference Between Friend Function And Virtual Function In C++

Difference Between Friend Function And Virtual Function In C++

BLUF: Mastering Difference Between Friend Function And Virtual Function In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Difference Between Friend Function And Virtual Function In C++

C++ is renowned for its efficiency. Learn how Difference Between Friend Function And Virtual Function In C++ enables low-level control and high-performance computing in the tutorial below.

In this tutorial, we will explore the variance between the Friend function and the Virtual function. However, prior to delving into their distinctions, it is essential to comprehend the Friend function and Virtual functions in the context of C++.

What is Friend Function?

In C++, a friend function is a function external to a class that can reach its private and protected components. This allows a friend function to interact with the private and protected members of a class similar to a member function, despite not being within the class itself. Friend functions are specified using the friend keyword within the class definition.

Characteristics of the Friend function:

There are various attributes of the friend function. Some key features of the friend function include:

  1. Not an Integral Part of the Class

In opposition to regular member functions, a friend function is defined within the class using the friend keyword; it exists external to the class structure.

  1. Gaining Entry to Private and Protected Members

By surpassing the encapsulation boundary, a friend function is able to retrieve private or protected members of the class it is associated with. This is done through the following

  1. Syntax.

Although the friend function declaration is defined outside of the class scope, it is commonly incorporated within the class declaration.

  1. Utilization

Necessary in scenarios where a function needs to interact with a class's private members without being part of the class itself.

What is the Virtual Function?

Runtime polymorphism in C++ is achieved by employing virtual functions. It enables calling the appropriate method during runtime using a pointer or reference to base class that points to objects of derived classes.

Characteristics of the Virtual function:

Some key attributes of the virtual function include:

  • Belonging to a Class

A virtual method is a member of a class that is specified with the virtual keyword, allowing subclasses to provide their own implementation.

  1. Polymorphism and Inheritance

In class structures, virtual methods are employed when a base class designates a function as virtual, allowing derived classes to implement it autonomously. This feature enables polymorphic behavior and facilitates Late Binding.

Late binding provides the flexibility to determine the suitable function implementation based on the type of object being referenced, as the specific function to execute is determined during runtime.

  1. Syntax

The virtual keyword is employed to specify virtual functions, which are defined in the base class. Subsequently, the override keyword is utilized by the derived class to replace this function.

  1. Application

It can be utilized when subclasses need to adjust their functionality and a parent class needs to offer a universal interface.

Example:

Let's consider an example to demonstrate the Friend function and Virtual function in C++:

Example

#include <iostream>
class Shape
{
public:
    Shape(int sides) : numSides(sides) {}
    virtual void draw() const
    {
        std::cout << "Drawing a generic shape with " << numSides << " sides." << std::endl;
    }
    int getNumSides() const
    {
        return numSides;
    }
private:
    int numSides;
};
class Circle: public Shape 
{
public:
    Circle() : Shape(0) {} 
    void draw() const override
    {
        std::cout << "Drawing a circle." << std::endl;
    }
};
void printNumSides(const Shape& shape) 
{
    std::cout << "Number of sides: " << shape.getNumSides() << std::endl;
}
int main()
{
    Circle circle;
    Shape genericShape(4); 
    std::cout << "Using virtual function:" << std::endl;
    circle.draw();         
    genericShape.draw();   
    std::cout << "\nUsing the friend function:" << std::endl;
    printNumSides(circle);         
    return 0;
}

Output:

Output

Using virtual function:
Drawing a circle.
Drawing a generic shape with 4 sides.
Using the friend function:
Number of sides: 0

Explanation:

  • There is a virtual function called draw and a private member called numSides in the Shape class.
  • Draw is overridden by the Circle class, which is inherited from Shape.
  • The friend function has access to the Shape class's private member numSides is printNumSides.
  • We generate an instance of Shape and Circle in the main function. After that, we draw shapes using the virtual function and print the number of sides using the friend function.
  • Differences between virtual and friend functions

There exist numerous distinctions between Virtual and Friend Functions. Here are some key variances between the virtual and friend function:

1. Scope

Friend Function: Even though a friend function is defined within a class, it is not considered a part of the class itself. This type of function is granted access to the private and protected members of the class it is associated with.

A virtual function is a method within a class that can be redefined in a subclass, enabling runtime polymorphism to be achieved through its utilization.

2. Access control

Friend Function: Acting as an ally of a class, it is granted access to the private and protected members within that class.

Virtual Method: This method is capable of being defined within the protected, private, or public areas of a class; nevertheless, the overriding function in the derived class must possess an equivalent access level.

3. Inheritance

Friend Function: Inherited by derived classes, a friend function acts as an independent function with privileged access to the private members of a class.

Derived classes have the capability to substitute the virtual function to provide their own unique implementation. This functionality is passed down to derived classes.

4. Invocation

Friend Function: Unlike regular member functions, a friend function is called without using a class object. It is invoked in the same manner as any other function.

Virtual Function: This type of function is invoked using a pointer or reference to a base class. The specific function that gets executed is determined by the object's type that the pointer or reference points to at runtime.

5. Polymorphism

Friend Function: Since it exists outside the class hierarchy, it does not participate in polymorphism.

Virtual functions enable polymorphism by allowing a program to invoke the correct function based on the actual type of the object during runtime.

Conclusion:

In summary, friend functions serve the purpose of granting non-member functions the ability to access private and protected members of a class, while virtual functions enable derived classes to override their implementation for achieving polymorphism. These features in C++ programming are versatile and find application in different scenarios.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience