The Wayback Machine - https://web.archive.org/web/20241008104012/https://www.geeksforgeeks.org/function-overriding-in-cpp/
Open In App

Function Overriding in C++

Last Updated : 01 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function is a block of statements that together performs a specific task by taking some input and producing a particular output. Function overriding in C++ is termed as the redefinition of base class function in its derived class with the same signature i.e. return type and parameters. It can be of both type: Compile Time and Runtime Polymorphism.

What is Function Overriding in C++?

Function overriding is a type of polymorphism in which we redefine the member function of a class which it inherited from its base class. The function signature remains same but the working of the function is altered to meet the needs of the derived class. So, when we call the function using its name for the parent object, the parent class function is executed. But when we call the function using the child object, the child class version will be executed.

Real-Life Example of Function Overriding

The best Real-life example of this concept is the Constitution of India. India took the political code, structure, procedures, powers, and duties of government institutions and set out fundamental rights, directive principles, and the duties of citizens of other countries and implemented them on its own; making it the biggest constitution in the world. 

Another Development real-life example could be the relationship between RBI(The Reserve Bank of India) and Other state banks like SBI, PNB, ICICI, etc. Where the RBI passes the same regulatory function and others follow it as it is.

Real-Life Example of Function Overriding

Function Overriding

Types of Function Overriding in C++

Unlike other languages such as Java where function overriding is strictly done at compile time, C++ supports two types of function overriding:

  • Compile Time Overriding
  • Runtime Function Overriding

Compile Time Function Overriding

In compile time function overriding, the function call and the definition is binded at the compilation of the program. Due to this, it is also called early binding or static binding.

Syntax
class Parent {
    access_modifier :
  
        // overridden function
        return_type name_of_the_function() {}
};

class child : public Parent {
    access_modifier :
  
        // overriding function
        return_type name_of_the_function() {}
};

Example of Compile Time Function Overriding

C++
// C++ program to demonstrate compile time function overriding

#include <iostream>
using namespace std;

class Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Base Function" << endl;
    }
};

class Child : public Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Derived Function" << endl;
    }
};

int main()
{
    Child Child_Derived;
    Child_Derived.GeeksforGeeks_Print();
    return 0;
}

Output
Derived Function

Runtime Function Overriding using Virtual Function

Unlike other languages like Java, the function overriding in C++ can be performed at both compile time and runtime. In all the above examples, the call to the overridden function is resolved during compile time. It is also called early binding where the function call is binded to its definition during compilation.

Function overriding can also be performed at the runtime, which means that function call will be binded to its definition during runtime (also known as late binding or dynamic binding). This can be done with the help of virtual functions.

Syntax
class Base {
public:
    virtual func()
    {
        // definition
    }
};

class Derived : public Base {
public:
    func() override
    {
        // new definition
    }
};


Here, override keyword tells the compiler that the given overridden function should be declared as virtual in the parent class. It is a kind of double check as the program can compile without errors even if the function is not virtual. But then, it will be compile time polymorphism and we won’t get the desired behaviour of the function overriding.

Example of Runtime Function Overriding using Virtual Function

C++
// C++ Program to illustrate how to implement runtime
// function overriding using virtual function
#include <iostream>
using namespace std;

class Base {
public:
    // Declare the function as virtual to allow overriding
    // in derived classes
    virtual void display()
    {
        cout << "Display method of Base class" << endl;
    }

    // Virtual destructor to ensure proper cleanup of
    // derived class objects
    virtual ~Base() {}
};

class Derived : public Base {
public:
    // Override the display method
    void display() override
    {
        cout << "Display method of Derived class" << endl;
    }
};

int main()
{
    Base* basePtr;
    Derived derivedObj;

    // Point base class pointer to derived class object
    basePtr = &derivedObj;

    // Call the display function
    // This will call the display method of the Derived
    // class due to the virtual function mechanism
    basePtr->display();

    return 0;
}

Output
Display method of Derived class

Advantages of Runtime Function Overriding

The following are the main advantages of function overriding:

  • Methods are selected at runtime based on object type.
  • Common interfaces and implementations can be reused as we only need to implement the interface for base class.
  • Changes in base classes automatically affect derived classes.
  • Facilitates the implementation of design patterns different design patterns.
  • Client code interacts with base class interface, not specific implementations reducing the coupling.

Limitations of Runtime Function Overriding

While runtime function overriding provides numerous advantages, it also comes with certain limitations:

  • Virtual function calls are generally slower than non-virtual function calls due to the indirection involved in the virtual table lookup.
  • Implementing and maintaining polymorphic code can be more complex compared to simpler non-polymorphic code.
  • Virtual tables and virtual pointers add to the memory overhead, especially in large systems with many classes.
  • Errors related to function overriding (e.g., incorrect signatures) might only be detected at runtime, leading to potential bugs.

Examples of Function Overriding in C++

Example 1: C++ Program to Call Overridden Function From Derived Class

C++
// C++ program to demonstrate function overriding
// by calling the overridden function
// of a member function from the child class

#include <iostream>
using namespace std;

class Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Base Function" << endl;
    }
};

class Child : public Parent {
public:
    void GeeksforGeeks_Print()
    {
        cout << "Derived Function" << endl;

        // call of original function
        Parent::GeeksforGeeks_Print();
    }
};

int main()
{
    Child Child_Derived;
    Child_Derived.GeeksforGeeks_Print();
    return 0;
}

Output
Derived Function
Base Function
Call Overridden Function From Derived Class

The output of Call Overridden Function From Derived Class

Example 2: C++ Program to Call Overridden Function Using Pointer

C++
// C++ program to access overridden function using pointer
// of Base type that points to an object of Derived class
#include <iostream>
using namespace std;

class Parent {
public:
    void GeeksforGeeks()
    {
        cout << "Base Function" << endl;
    }
};

class Child : public Parent {
public:
    void GeeksforGeeks()
    {
        cout << "Derived Function" << endl;
    }
};

int main()
{
    Child Child_Derived;

    // pointer of Parent type that points to derived1
    Parent* ptr = &Child_Derived;

    // call function of Base class using ptr
    ptr->GeeksforGeeks();

    return 0;
}

Output
Base Function

Example 3: C++ Program to Access of Overridden Function using Child Class Object

C++
// C++ program to access overridden function
// in main() using the scope resolution operator ::

#include <iostream>
using namespace std;

class Parent {
public:
    void GeeksforGeeks()
    {
        cout << "Base Function" << endl;
    }
};

class Child : public Parent {
public:
    void GeeksforGeeks()
    {
        cout << "Derived Function" << endl;
    }
};

int main()
{
     Child Child_Derived;
     Child_Derived.GeeksforGeeks();

    // access GeeksforGeeks() function of the Base class
     Child_Derived.Parent::GeeksforGeeks();
    return 0;
}

Output
Derived Function
Base Function
Access of Overridden Function to the Base Class

Access of Overridden Function to the Base Class

 Function Overloading Vs Function Overriding

Function Overloading

Function Overriding

It falls under Compile-Time polymorphismIt can be both Compile Time or Runtime Polymorphism
A function can be overloaded multiple times as it is resolved at Compile timeA function cannot be overridden multiple times as it is resolved at Run time 
Can be executed without inheritanceCannot be executed without inheritance
They are in the same scopeThey are of different scopes.

To know more, you can refer to Function Overloading VS Function Overriding.




Previous Article
Next Article

Similar Reads

Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include <iostream> using namespace std; class Gfg { public: void printHello() { cout << "hello gfg-class specific" << endl; } }; void printHello() { cout << "hello gf
5 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 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 Friend Function and Virtual Function in C++
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
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 &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 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
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 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
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include <i
3 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
wcscpy() function in C++ with Examples
The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination. Syntax: wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); Parameters: This method accepts the following two parameters: dest: specifies the pointer to the destination array. src: specifies the pointer
1 min read
wcscmp() function in C++ with Examples
The wcscmp() function is defined in cwchar.h header file. The wcscmp() function is used to compares two null terminating wide string and this comparison is done lexicographically. Syntax: int wcscmp(const wchar_t* str1, const wchar_t* str2); Parameters: This method takes the following two parameters: str1: This represents the pointer to the first s
2 min read
strtoul() function in C/C++
The strtoul() function in C/C++ which converts the initial part of the string in str to an unsigned long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. This function discard any white space characters until the first non-whitespace character is found, then takes as many characters as poss
3 min read
wcscspn() function in C/C++
The wcscspn() function in C/C++ searches the first occurrence of a wide character of string_2 in the given wide string_1. It returns the number of wide characters before the first occurrence of that wide character . The search includes the terminating null wide characters. Therefore, the function will return the length of string_1 if none of the ch
2 min read
asctime() function in C++
The asctime() function is defined in the ctime header file. The asctime() function converts the given calendar time of structure tm to a character representation i.e human readable form. Syntax: char* asctime(const struct tm * time_ptr); Parameter: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted. Return
1 min read
Measure execution time of a function in C++
We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constr
3 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
exp() function C++
The exp() function in C++ returns the exponential (Euler's number) e (or 2.71828) raised to the given argument. Syntax for returning exponential e: result=exp() Parameter: The function can take any value i.e, positive, negative or zero in its parameter and returns result in int, double or float or long double. Return Value: The exp() function retur
2 min read
copysign() function in C++
copysign(x, y) function returns the value with a magnitude of x and the sign of y. Examples: Input : copysign(6, -2) Output : -6 Input : copysign(-6, 2) Output : 6 Syntax: copysign(x, y); Parameters: x : Value with the magnitude y : Value with the sign Returns : Returns the value with a magnitude of x and the sign of y. Return type follows type cas
1 min read
vector rbegin() and rend() function in C++ STL
vector::rbegin() is a built-in function in C++ STL which returns a reverse iterator pointing to the last element in the container. Syntax: vector_name.rbegin() Parameters: The function does not accept any parameter.Return value: The function returns a reverse iterator pointing to the last element in the container.Program to demonstrate the vector::
2 min read
wcschr() function in C++
wcschr() function in C++ searches for the first occurrence of a wide character in a wide string. The terminating null wide character is considered part of the string. Therefore, it can also be located in order to retrieve a pointer to the end of a wide string. Syntax: const wchar_t* wcschr (const wchar_t* ws, wchar_t wc) wchar_t* wcschr ( wchar_t*
2 min read
quick_exit() function in C++ with Examples
The quick_exit() function is defined in the stdlib header file. The quick_exit() function is used for normal termination of a process without completely cleaning the resources. If val is zero or EXIT_SUCCESS, it shows successful termination of program.If the value is non-zero or EXIT_FAILURE, it shows that the program is not successfully terminated
1 min read
unordered_multimap begin() and end() function in C++ STL
The unordered_multimap::begin() is a built-in function in C++ STL that returns an iterator pointing to the first element in the container or to the first element in one of its buckets. Syntax: unordered_multimap_name.begin(n) Parameters: The function accepts one parameter. If a parameter is passed, it returns an iterator pointing to the first eleme
5 min read
list cbegin() and cend() function in C++ STL
The list::cbegin() is a built-in function in C++ STL which returns a constant random access iterator which points to the beginning of the list. Hence the iterator obtained can be used to iterate container but cannot be used to modify the content of the object to which it is pointing even if the object itself is not constant.Syntax: list_name.cbegin
2 min read
towctrans() function in C/C++
The towctrans() is a built-in function in C/C++ which applies a transformation to the wide character wc specified by desc. It is defined within the cwctype header file of C/C++. Syntax: wint_t towctrans(wint_t wc, wctype_t desc) Parameter: The function accepts two mandatory parameter which are described below: wc - The wide character which needs to
2 min read
iswcntrl() function in C/C++
The iswcntrl() is a built-in function in C++ STL which checks if the given wide character is a control character or not. It is defined within the cwctype header file of C/C++. Syntax: int iswcntrl(wint_t ch) Parameter: The function accepts a single mandatory parameter ch which specifies the wide character which we have to check that if it is a cont
2 min read
bitset all() function in C++ STL
The bitset::all() is a built-in function in C++ STL which returns True if all bits are set in the binary representation of a number if it is initialized in the bitset. It returns False if all the bits are not set. Syntax: bool bitset_name.all() Parameter: This function does not accepts any parameter. Return Value: The function returns a boolean val
2 min read
atan2() function in C++ STL
The atan2() is an inbuilt function in C++ STL which returns tangent inverse of (y/x), where y is the proportion of the y-coordinate and x is the proportion of the x-coordinate. The numeric value lies between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and positive x-axis. It is the counterclockwise
3 min read
Article Tags :
Practice Tags :