In programming, a function is a code designed to perform a specific task within a program. To understand function overriding, it’s crucial first to understand inheritance. In Object-Oriented Programming (OOP), inheritance is a fundamental concept that allows a new class to inherit properties and behaviors from its parent class, promoting code reuse and hierarchical structuring.
Function overriding, also called method overriding in C++, is significant in this framework. It allows a derived class to override or replace a function inherited from its parent class, providing a tailored implementation to suit its unique requirements. This process holds substantial significance in OOP, allowing programmers to create specialized versions of functions in derived classes to enhance the adaptability and customization of the codebase.
Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members and the member functions present in the parent class. If you wish to override any functionality in the child class, you can implement function overriding. Function overriding means creating a newer version of the parent class function in the child class.
Check out our free courses to get an edge over the competition.
Dive in to learn more about what is method overriding in C++.
What is Functional Overriding in C++?
Function overriding or method overriding in C++ lets you replace an existing function in a specific derived class with a new version. This becomes handy when a child class needs its unique version of a function.
It grants the child class access to the parent class’s functions and plays a pivotal role in achieving polymorphism. It allows a program to execute the appropriate version of a function based on the object’s type during runtime.
Introducing dynamic polymorphism through function override in C++ fosters a more versatile and adaptable code structure. This characteristic becomes particularly valuable when a single function name can exhibit different behaviors across various derived classes.
Advantages of Using Function Override in C++
Overriding brings a powerful dimension to object-oriented programming, offering advantages that contribute to code flexibility and efficiency.
- Polymorphism: Overriding allows a program to execute the appropriate version of a function based on the object’s type during runtime, enhancing flexibility and adaptability, thereby making it a backbone of polymorphism.
- Code reusability: Developers can reuse existing code by inheriting functions from a base class and overriding them in derived classes. This promotes a more efficient and organized code structure.
- Customization: Overriding enables the customization of inherited functionality in derived classes. This is particularly useful when a specific class requires a modified or enhanced version of a function inherited from its parent class.
- Enhances code readability: The override function in C++ helps create class hierarchies, promoting a structured and organized codebase. This hierarchical arrangement simplifies code maintenance and readability.
- Keeping codes clean: With method overriding in C++, you can use the same function name for different tasks, making the code cleaner. This reduces confusion in naming and simplifies the code, making it easier to understand.
- Saves memory: Overriding enhances memory efficiency by avoiding unnecessary duplication, ensuring a consistent and streamlined code structure. This not only promotes clarity but also facilitates ease of maintenance.
Adaptability: The override function in C++ enables programmers to create specialized versions of functions in derived classes and enhances the overall adaptability of the code. This is crucial for accommodating varying requirements in different parts of the program.
C++ Functions
A C++ function is a group of statements that come together to perform a task. Every program has at least a main() function and certain programs can have additional functions.
The function declaration conveys to the compiler the function name, parameters and return type. A function definition determines the function body. The C++ standard library consists of many built-in functions that the program can call. A function can be a method, a procedure, or a subroutine.
Methods in object-oriented programming encapsulate actions within classes, promoting code organization and reusability. Procedures are task-oriented, executing specific functions without returning a value. Subroutines emphasize reusability, enabling developers to invoke a set of instructions multiple times, thereby enhancing code efficiency and minimizing redundancy. This structured approach contributes to a more organized and efficient codebase in C++.
C++ supports various types of functions, each serving specific purposes in programming. Here are some of the key types of functions in C++:
- Standalone Functions: Standalone functions are independent of any class and can be called from any part of the program. These functions are often used for general-purpose tasks that don’t necessarily require access to specific class data.
- Member Functions: Member functions are associated with a specific class. They have access to the private and protected members of the class and operate on the class’s data. Member functions are called using instances of the class.
- Inline Functions: When declared inline, the compiler inserts the code of the function directly at the call site, reducing the overhead of a function call. This optimization is beneficial for small, frequently called functions where the call cost is high compared to the function’s execution.
- Recursive Functions: Recursive functions call themselves either directly or indirectly. They are commonly employed to address problems that can be segmented into smaller instances of the identical issue. Each recursive call operates on a smaller subset of the original problem until a base case is reached, providing an effective solution to certain problems.
- Friend Functions: Friend functions are not members of a class but are granted access to its private and protected members. This allows them to operate on the class’s data without being part of it. Friend functions often provide specific functionalities that require access to private members but don’t naturally belong to the class.
- Default Arguments: Functions in C++ can have default arguments, meaning certain parameters are given default values. This allows the caller to omit those arguments when calling the function, and the default values will be used. This feature enhances the flexibility of functions, making them more adaptable to different use cases.
Check out Java Bootcamp from upGrad.
Defining a Function
To define a function in C++, you begin with the function’s return type, followed by the function name and any required parameters enclosed in parentheses.
The general syntax of a C++ function is:
return_type function_name(parameter list) {
function body
}
Any C++ function comprises a function header and a body. The components of a C++ function are:
Return Type –The return type represents the type of the function’s return value.
It indicates what kind of data the function will provide back to the part of the program that called it. For example, a function with an int return type would provide an integer value.
Function Name- This denotes the name of the function. The function name along with the parameter list make up the function signature.
It serves as a unique identifier in the program. A well-chosen name reflects the purpose of the function, enhancing code readability and understanding.
Parameters – A parameter is a placeholder for the value returned by the function. When a function is called, a value is passed to the parameter which is called the actual parameter.
Parameters enable the function to receive input values, making it versatile and adaptable to different scenarios. They act as connectors, allowing information to flow into the function.
Function Body- The function body constitutes the list of statements that define what the function will do.
It is the heart of the function, containing the instructions that execute when the function is called. The function body encapsulates the logic and operations, providing a clear structure for the function’s purpose within the overall program.
Calling a Function
To use a function in C++, you must invoke or call the function. The control is transferred to the function, the function then performs the desired task, and the return statement returns the control back to the main program.
You need to pass the required parameters including the function name to call a function. If the function returns a value, then the value can be stored. There are a few ways in which arguments can be passed to a function while calling it. The call types are Call by Value, Call by Reference, and Call by Pointer.
- Call by Value
In Call by Value, a copy of the actual parameter is passed to the function. This method ensures the original data remains unchanged, as the function operates on a duplicate. While it provides a simple and safe approach, it may be less efficient for large datasets due to the need to duplicate data.
- Call by Reference
On the other hand, Call by Reference passes the memory address of the actual parameter to the function. Changes made within the function directly affect the original data, offering efficiency in memory usage by avoiding the creation of duplicates. This method provides a direct connection to the actual data, enhancing performance.
- Call by Pointer
Call by Pointer shares similarities with Call by Reference, using pointers to achieve the same effect. Instead of passing the memory address directly, a pointer—a variable storing the memory address—is passed to the function. This method combines the efficiency of direct data access with the control provided by pointers, striking a balance between the two approaches.
Check out upGrad’s Full Stack Development Bootcamp
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Function Overriding in C++ Explained With Examples
When a derived class or child class defines a function that is already defined in the base class or parent class, it is called function overriding in C++. Function overriding helps us achieve runtime polymorphism and the enables programmers to perform the specific implementation of a function already used in the base class.
The dynamic capability of the overriding member function in C++ makes your code more flexible and customizable, allowing for a versatile and advanced programming approach in C++.
Example:
Study the example given above. Here the parent class is “Base” and the child class is “Derived”.
The output of the above program will be:
Derived Function
The function print() is declared in both the Base and Derived classes. When we call the function print() through the Derived class object, “derived1”, the print() from the Derived class is invoked and executed by overriding the same function of the Base class.
Working of the Function Overriding Principle
As you can see from the above image, the Base class function was overridden because we called the same function through the object of the Derived class.
If we call the print() function through an object of the Base class, the function will not be overridden. For e.g.:
//Call function of Base class
Base base1;
base1.print(); // Output: Base Function
The output of the above code will be:
Base Function
In-Demand Software Development Skills
How to access Overridden Functions in C++
You must use the scope resolution operator, “::” to access the overridden function. Another way to access the overridden function is by using the pointer of the base class to point to an object of the derived class and calling the function through the pointer.
Example:
The output of the above program will be:
Derived Function
Base Function
Working of the Access of overridden function
Here the statement derived 1.print() accesses the print() function of the Derived class and the statement derived2.Base::print() accesses the print() function of the Base class.
Calling a C++ overridden function from the derived class
In this code, we call the overridden function from within the Derived class itself.
Working of the overridden function call from the Derived class
The Base::print() command calls the overridden function from inside the Derived class.
Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Explore our Popular Software Engineering Courses
Function Overloading vs. Function Overriding
Function overloading and overriding in C++ are two essential concepts, each contributing to the versatility and efficiency of code in distinct ways.
Function overloading is achieved at compile time and can be done in the base class and derived class. It helps to provide multiple definitions of the functions by changing the signature of the functions such as data type of parameters or return types.
Function overriding is achieved at runtime. In overriding, the base class is redefined in the derived class with the same return type and parameters.
Both function overloading and overriding in C++ serve as valuable tools for developers, providing ways to streamline code, enhance adaptability, and optimize the efficiency of C++ programs.
Other differences between function overriding and function overloading in C++ are:
1. Inheritance
Function overriding can be used only with class inheritance while function overloading does not require class inheritance.
Overriding inheritance methods in C++ enables a derived class to provide a specific implementation for a function inherited from its base class. However, function overloading is more versatile and not bound by the constraints of class relationships.
2. Function Signature
Overloaded functions differ in signature either in the number of parameters or the type of parameters. In function overriding, the function signatures remain the same.
Function overloading allows developers to create multiple versions of a function with variations in the input parameters, catering to different use cases. On the other hand, an overridden function in the derived class seamlessly replaces the base class function, preserving the expected interface.
3. Function Scope
Overridden functions vary in scope while overloaded functions have the same scope.
Explore Our Software Development Free Courses
Function overriding introduces the concept of dynamic polymorphism, where the function’s scope is determined at runtime based on the object’s type. This dynamic binding provides flexibility but introduces scope variations. On the other hand, function overloading, being resolved at compile time, maintains a consistent scope across all overloaded versions of the function.
4. Function Behavior
Function overriding is essential when a derived class function must perform differently or with added functionality than the base class function. Function overloading is implemented when functions with the same name need to have different behaviours depending upon the parameters passed to them.
If you’re interested to learn more about full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
What is function overriding?
Function overriding is a concept in object-oriented programming which allows a function within a derived class to override a function in its base class, but with a different signature (and usually with a different implementation). A key aspect of this is that it is not possible for the derived class to “undo” the changes to the base class, or at least it is not possible without editing the base class further. A common use of function overriding is to provide a default implementation in the base class, and then overriding with a specific implementation in the derived class.
What are the differences between function overriding and overloading?
Function overriding occurs when you create function with the same name as a function that already exists in a base class. When this happens, the new function will replace the existing function and can be used in place of the original function. Overloading occurs when you create functions with the same name but different parameters. When this happens, the new function will be called in addition to the original function, and both functions can be used in any context without any problem.
What is inheritance in C++?
Inheritance in C++ is a pivotal Object-Oriented Programming (OOP) concept, facilitating the transfer of attributes and behaviors from a base (parent) class to a derived (child) class. This establishes a hierarchy, promoting code reuse and modular design. Overriding inheritance methods in C++ complements this by allowing a derived class to furnish a unique implementation for a function inherited from the base class. This customization enhances code flexibility, enabling each derived class to tailor the behavior of inherited methods to meet its specific requirements.
How to avoid function overriding in C++?
To prevent function overriding in C++, use the 'final' keyword when declaring a member function in the base class. This specifier restricts derived classes from overriding that particular function, ensuring its behavior remains consistent throughout the inheritance hierarchy.