- Blog Categories
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Function Overriding in C++ [Function Overloading vs Overriding with Examples]
Updated on 15 November, 2024
94.69K+ views
• 16 min read
Table of Contents
Function overloading and overriding in C++ are powerful ways to make code flexible and specific. Imagine Ford, the car company, which produces various vehicles. Each vehicle inherits basic features like the brand name and type, but each model can also have unique features. A sports car, for instance, is still a car but might have different handling or engine specifications.
In C++ library, function overloading allows you to define multiple versions of a function, each with different parameters. This means you can use the same function name but adapt it for different situations. Function overriding, on the other hand, lets a derived class (like the sports car) replace a function inherited from a parent class, allowing each version to fit specific needs.
Studies show that around 75% of C++ projects rely on these methods to keep code clear and easy to work with. In this article, we’ll go over the basics of function overloading and overriding in C++ with examples to help you understand clearly.
What is Function Overloading in C++?
Function overloading in C++ is a feature of object-oriented programming. It allows multiple functions to share the same name within the same scope but differ in the number or type of parameters. This feature enables you to define different versions of a function that handle varying inputs without needing separate function names. When the program runs, the compiler selects the correct version based on the provided arguments. This process is known as compile-time polymorphism. Function overloading is particularly useful for performing similar operations on different types of data or varying numbers of arguments.
Key Aspects of Function Overloading in C++
1. Parameter Type Variation
Function overloading can be achieved by changing the data types of parameters. For instance, you can create two versions of the same function with different parameter types and allow a single function name to handle multiple data types.
cpp
void display(int number) {
cout << "Integer: " << number << endl;
}
void display(double number) {
cout << "Double: " << number << endl;
}
In this example, the display() function is overloaded. One version accepts an int, while the other accepts a double. This lets you use display() for both integer and floating-point numbers without creating two separate function names.
2. Parameter Count Variation
Another way to overload functions is by changing the number of parameters they accept. For example, you could design a function to perform a task differently based on whether it receives one, two, or more arguments.
cpp
int calculateArea(int side) {
return side * side; // Area of a square
}
int calculateArea(int length, int width) {
return length * width; // Area of a rectangle
}
Here, calculateArea() is overloaded. With one parameter, it calculates the area of a square. With two parameters, it computes the area of a rectangle. This flexibility makes the code more readable and easier to use.
Why Use Function Overloading?
Improves Readability:
Overloading makes your code easier to understand. Using the same name for similar functions makes it clear that each version relates to the same concept but with different details.
Reduces Code Redundancy:
Overloading helps avoid redundant code by eliminating the need for multiple distinct function names. This reduces clutter and helps keep your codebase clean.
Enables Compile-Time Polymorphism:
Overloading allows the program to determine the correct function version at compile-time based on arguments. This ensures the program runs more efficiently and avoids errors.
Become a Full-Stack Developer. Enroll in upGrad’s courses today!
Practical Example: Parameter Type and Count Overloading
Here’s an example combining both parameter type and count variations for an add() function. Each version is suited to different input combinations:
cpp
// Adding two integers
int add(int a, int b) {
return a + b;
}
// Adding three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Adding two floating-point numbers
double add(double a, double b) {
return a + b;
}
In this setup:
- add(int, int) adds two integers.
- add(int, int, int) handles three integers.
- add(double, double) manages two floating-point numbers.
When you call add(), the compiler will automatically choose the correct version. It does this by matching the argument types and counts with the appropriate function definition.
What is Function Overriding in C++?
In C++, function overriding lets a derived class redefine a function inherited from its base class. Unlike function overloading, which involves functions with the same name but different parameters, function overriding requires an exact match in the function name, parameters, and return type between the base and derived class functions. This feature is essential for runtime polymorphism, as it allows the program to determine which function to call based on the object type at runtime rather than compile-time. Overriding a function provides flexibility, which enables derived classes to give specialized behavior to an inherited function.
Key Aspects of Function Overriding in C++
1. Basic Function Overriding
In basic function overriding, the derived class redefines a method inherited from the base class without using any special keywords. This redefined function in the derived class replaces the base class’s function when accessed through a derived class object. However, without the virtual keyword, there’s no polymorphic behavior.
cpp
class Animal {
public:
void speak() {
cout << "Animal speaks." << endl;
}
};
class Dog : public Animal {
public:
void speak() { // Overrides speak() in Animal
cout << "Dog barks." << endl;
}
};
Here, speak() in the Dog class overrides speak() in Animal. If we create a Dog object and call speak(), the output will be "Dog barks." This demonstrates basic function overriding.
2. Virtual Function Overriding
To achieve true polymorphism, we use virtual functions. Declaring a function as virtual in the base class allows the derived class to override it. When accessed through a base class pointer or reference, the program calls the overridden function in the derived class, enabling dynamic binding.
cpp
class Shape {
public:
virtual void draw() { // Virtual function in base class
cout << "Drawing shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() override { // Overrides draw() in Shape
cout << "Drawing circle." << endl;
}
};
In this example, draw() in Shape is a virtual function, allowing Circle to override it. If we create a Shape pointer that points to a Circle object and call draw(), the Circle’s draw() function will execute, showcasing polymorphic behavior.
3. Non-Virtual Function Overriding
Function overriding without virtual limits polymorphism. Overriding a non-virtual function in the derived class simply replaces the base class’s version, but only for derived class objects. This approach is uncommon in OOP as it lacks the flexibility of dynamic binding.
cpp
class Vehicle {
public:
void info() { // Non-virtual function
cout << "This is a vehicle." << endl;
}
};
class Car : public Vehicle {
public:
void info() { // Overrides info() in Vehicle
cout << "This is a car." << endl;
}
};
Here, info() in Vehicle is overridden in Car, but without the virtual keyword. Calling info() on a Vehicle pointer to a Car object would execute Vehicle’s info() rather than Car’s, showing no polymorphism.
Why Use Function Overriding?
Enhanced Flexibility:
Function overriding lets derived classes tailor inherited functionality, making classes more adaptable and suitable for specific tasks.
Runtime Polymorphism:
Virtual function overriding supports runtime polymorphism, allowing C++ to dynamically bind function calls based on the actual object type. This is essential for creating flexible, extensible code.
Code Reusability:
By allowing derived classes to build on and modify base class functions, overriding encourages reusing and adapting code rather than duplicating it.
Example Code Demonstrating Polymorphism through Virtual Function Overriding
This example uses a base Animal class with a virtual function sound() and derived classes Dog and Cat, each with its own version of sound().
cpp
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Some generic animal sound." << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Overrides sound()
cout << "Woof Woof." << endl;
}
};
class Cat : public Animal {
public:
void sound() override { // Overrides sound()
cout << "Meow." << endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->sound(); // Outputs: Woof Woof
animal2->sound(); // Outputs: Meow
delete animal1;
delete animal2;
return 0;
}
In this example:
- The sound() function is virtual in Animal.
- Dog and Cat classes override sound() with their implementations.
- The program uses a base class pointer to call the correct function at runtime, demonstrating polymorphic behavior.
Function Overloading vs. Function Overriding: Key Differences
In C++, function overloading and function overriding provide distinct ways to handle functions, each with its own purpose and application.
Function overloading happens at compile-time and allows multiple functions with the same name but different parameters (varying by type or count) to exist in a class. This improves readability and makes it easy to use one function name to handle different types of inputs. Overloading doesn’t rely on inheritance, so it can be used within a single class.
Function overriding, in contrast, takes place at runtime and requires inheritance. It lets a derived class define its own version of a function that’s already in the base class, supporting polymorphism. This means the function used depends on the object’s actual type when called.
Key distinctions between function overloading and overriding include:
- Inheritance Requirement
- Overloading: No inheritance is needed and can be done within one class.
- Overriding: Requires inheritance, with the derived class function replacing the base class function.
- Timing
- Overloading: Happens at compile-time, with the compiler choosing the function based on parameter types and counts.
- Overriding: Occurs at runtime, allowing the program to select the derived class function when accessed through a base class reference.
- Function Signature
- Overloading: Requires different signatures—either the number or type of parameters changes.
- Overriding: Requires identical function signatures in the base and derived classes.
- Binding and Scope
- Overloading: Uses static binding, determined by the compiler.
- Overriding: Uses dynamic binding, where the function called is based on the object’s type at runtime.
- Purpose
- Overloading: Provides options to perform similar tasks on different data.
- Overriding: Allows the derived class to modify or add to the base class function.
Summary Table
Feature |
Function Overloading |
Function Overriding |
Purpose |
Same name, different parameters |
Modify base function in derived class |
Inheritance |
Not required |
Required |
Timing |
Compile-time |
Runtime |
Function Signature |
Varies by parameter types or count |
Identical in base and derived classes |
Binding |
Static binding |
Dynamic binding |
Use Case |
Multiple operations with the same name |
Extend base class functionality |
Examples of Function Overloading in C++
Function overloading allows developers to define multiple functions with the same name but different parameters. This makes code more flexible and reusable, as it enables performing similar tasks on different data types or structures. Below, we'll explore practical examples of function overloading to calculate areas for different shapes.
Example 1: Function Overloading for display() Function
This example demonstrates overloading the display() function to output different data types: an integer and a string. By overloading, we can use the same function name display() to print either an integer or a string, depending on the input parameter.
Code Example
cpp
#include <iostream>
using namespace std;
// Function to display an integer
void display(int num) {
cout << "Integer: " << num << endl;
}
// Overloaded function to display a string
void display(string text) {
cout << "String: " << text << endl;
}
int main() {
display(25); // Calls the integer version of display
display("Hello!"); // Calls the string version of display
return 0;
}
Output
makefile
Integer: 25
String: Hello!
Explanation
- The display(int num) function is designed to print an integer value. When we pass an integer to display(), this version is called.
- The display(string text) function is designed to print a string. When we pass a string to display(), this version is called.
- This way, we only need to remember one function name, display(), which can handle different types of input based on the data type passed. The compiler automatically selects the correct version of display() based on whether we pass an integer or a string.
Example 2: Function Overloading for multiply() Function
This example shows the overloading of the multiply() function to perform multiplication on different data types: two integers, and a double with an integer.
Code Example
cpp
#include <iostream>
using namespace std;
// Function to multiply two integers
int multiply(int a, int b) {
return a * b;
}
// Overloaded function to multiply a double and an integer
double multiply(double a, int b) {
return a * b;
}
int main() {
int intResult = multiply(4, 5); // Calls the integer version of multiply
double doubleResult = multiply(3.5, 2); // Calls the double version of multiply
cout << "Multiplication of integers: " << intResult << endl;
cout << "Multiplication of double and integer: " << doubleResult << endl;
return 0;
}
Output
php
Multiplication of integers: 20
Multiplication of double and integer: 7
Explanation
- multiply(int a, int b) is defined to take two integer values, multiply them, and return the result as an integer.
- multiply(double a, int b) is defined to take a double and an integer, multiply them, and return the result as a double.
- When multiply(4, 5) is called with two integers, it invokes the first function, which returns 20.
- When multiply(3.5, 2) is called with a double and an integer, it invokes the second function, which returns 7.0.
This example highlights how we can use the same function name, multiply(), to perform different operations based on input types, streamlining the code while keeping it versatile.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Examples of Function Overriding in C++
In function overriding, a child class changes the behavior of a function it inherits from a parent class. This lets the child class define its own version of the function while keeping the original function in the parent class. Let’s use an easy example to understand this.
Imagine the RBI (Reserve Bank of India) as a parent class. It sets up basic banking rules like loan_policy() and insurance_policy(). Now, banks like SBI and HDFC inherit from RBI, but each bank has its own loan policy. With function overriding, SBI and HDFC can each create their specific loan policy, even though they follow RBI’s main rules.
Example 1: RBI and Banks with Overriding Services
Here’s an example in C++ to show how RBI as the parent class has a loan_policy() function, which is then overridden by SBI and HDFC.
cpp
#include <iostream>
using namespace std;
// Parent class representing RBI
class RBI {
public:
// RBI's loan policy
virtual void loan_policy() {
cout << "RBI Loan Policy: Standard interest rate.\n";
}
};
// Child class representing SBI
class SBI : public RBI {
public:
// SBI's loan policy
void loan_policy() override {
cout << "SBI Loan Policy: Special rate for SBI customers.\n";
}
};
// Child class representing HDFC
class HDFC : public RBI {
public:
// HDFC's loan policy
void loan_policy() override {
cout << "HDFC Loan Policy: Premium rate for HDFC customers.\n";
}
};
int main() {
RBI* rbi_ptr;
SBI sbi;
HDFC hdfc;
// Using RBI pointer to access overridden functions
rbi_ptr = &sbi;
rbi_ptr->loan_policy(); // Calls SBI's loan_policy
rbi_ptr = &hdfc;
rbi_ptr->loan_policy(); // Calls HDFC's loan_policy
return 0;
}
Output
rust
SBI Loan Policy: Special rate for SBI customers.
HDFC Loan Policy: Premium rate for HDFC customers.
Explanation
- RBI sets a general loan policy.
- SBI and HDFC each override this with their own loan policies.
- Using an RBI pointer, we can access the specific loan policies of each bank, thanks to polymorphism.
- Example 2: Overriding with an Analogy - Constitutions
Let’s consider the Constitution as the parent class. Different countries take inspiration from other constitutions but customize them to fit their own needs. Here, we’ll create a base class Constitution with a general law_system() method. Then, USA_Constitution and UK_Constitution override this method with their specific systems.
cpp
#include <iostream>
using namespace std;
// Parent class representing general Constitution
class Constitution {
public:
virtual void law_system() {
cout << "General Law System: Basic legal framework.\n";
}
};
// Child class representing USA's legal system
class USA_Constitution : public Constitution {
public:
void law_system() override {
cout << "USA Legal System: Presidential system with checks and balances.\n";
}
};
// Child class representing UK’s legal system
class UK_Constitution : public Constitution {
public:
void law_system() override {
cout << "UK Legal System: Parliamentary system with monarchy.\n";
}
};
int main() {
Constitution* const_ptr;
USA_Constitution usa;
UK_Constitution uk;
const_ptr = &usa;
const_ptr->law_system(); // Calls USA's law_system
const_ptr = &uk;
const_ptr->law_system(); // Calls UK's law_system
return 0;
}
Output
sql
USA Legal System: Presidential system with checks and balances.
UK Legal System: Parliamentary system with monarchy.
Explanation
- Constitution provides a general law_system().
- USA_Constitution and UK_Constitution override this with their own systems.
- The base pointer Constitution* lets us access the specific legal system for each country.
Common Mistakes in Function Overloading and Overriding in C++
When working with function overloading and overriding in C++, some mistakes are easy to make. Here’s a guide to avoid the most common ones, with examples for clarity.
1. Forgetting the virtual Keyword in the Base Class
- Problem: If the base class function isn’t marked as virtual, overriding won’t work as expected. The base class function will be called instead of the derived one, especially when using a base class pointer.
Example:
cpp
class Base {
// Missing virtual keyword
void display() { std::cout << "Base class\n"; }
};
class Derived : public Base {
void display() { std::cout << "Derived class\n"; }
};
int main() {
Base* obj = new Derived();
obj->display(); // Outputs: "Base class" instead of "Derived class"
return 0;
}
Fix: Add virtual to the base class function to enable overriding.
2. Overloading with Identical Parameter Types
- Problem: Attempting to overload functions with the same parameters doesn’t work. The compiler won’t know which function to call, resulting in a compilation error.
Example:
cpp
class Test {
void calculate(int x) { /*...*/ }
void calculate(int y) { /*...*/ } // Error: Same parameter type
};
Solution: Ensure each overloaded function has a unique signature by changing parameter types or the number of parameters.
3. Incorrect Use of Scope Resolution in Overriding
- Problem: Using the scope resolution operator :: when calling a function directly on an object will call the base class function, not the overridden one. This can be confusing if you meant to use the derived class version.
Example:
cpp
class Animal {
public:
virtual void sound() { std::cout << "Some animal sound\n"; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "Bark\n"; }
};
int main() {
Dog dog;
dog.Animal::sound(); // Calls Animal's sound() instead of Dog's
return 0;
}
Tip: Use the scope resolution operator with the base class only if you want to explicitly call the base function.
Quick Reminders:
- Add virtual to any base function you plan to override in a derived class.
- Make sure overloaded functions have unique parameter signatures.
- Avoid unnecessary scope resolution to prevent accidentally calling the base class function.
Learn C++ Programming
If you’re curious about coding or want to strengthen your programming skills, our C++ tutorials are designed just for you. These tutorials break down C++ in simple, clear steps, helping you learn at your own pace with real examples and practical exercises.
What You’ll Get:
- 77 Short Lessons: Learn C++ basics and advanced topics in easy-to-manage chunks.
- 15 Hours of Learning: Perfect for fitting around your schedule.
- Practical Coding Examples: Understand concepts by actually using them.
- Pro Tips from Experts: Discover tips to write cleaner, more efficient code.
- Build Real Skills: Get confident with C++ and be ready for real-world projects.
Start your C++ journey with upGrad’s tutorials—your first step into programming awaits!
Advance your tech career with our Popular Software Engineering Courses, featuring practical projects and industry-relevant skills to make you job-ready.
Explore our Popular Software Engineering Courses
Stay ahead in the tech world by learning essential software development skills, including cloud computing, API integration, and version control systems.
In-Demand Software Development Skills
Jumpstart your coding journey with our Free Software Development Courses, covering core programming concepts and practical skills at no cost.
Explore Our Software Development Free Courses
Frequently Asked Questions (FAQs)
1. Why is function overriding essential for object-oriented programming in C++?
Function overriding allows derived classes to provide specific implementations of functions inherited from base classes. This feature is important in C++ as it supports polymorphism, enables dynamic behavior and flexibility in handling objects of different classes uniformly.
2. Can you override a function without using the virtual keyword?
No, in C++ the virtual keyword is necessary in the base class to enable function overriding. Without it, the derived class function would not override but hide the base class function instead, leading to unexpected results.
3. How does function overriding improve code readability and maintainability?
Function overriding makes the code modular and adaptable by allowing derived classes to define specific behaviors. It helps keep the base class general while allowing specializations in derived classes, which improves readability and maintainability by localizing changes.
4. What are the performance implications of using function overloading in C++?
Function overloading is resolved at compile-time, so it has minimal performance impact. However, defining multiple functions with the same name may increase code size slightly. Generally, overloading does not significantly affect runtime performance.
5. How can you prevent a derived class from overriding a base class function?
In C++, you can prevent a function from being overridden by marking it as final in the base class. This restriction ensures that no derived class can provide its version of the function.
6. Is it possible to overload operators in C++?
Yes, C++ allows operator overloading, enabling developers to redefine how operators work for user-defined types. This feature is used frequently in classes where arithmetic operations or comparisons are necessary.
7. How does function overriding differ in C++ compared to other programming languages?
While function overriding concepts are similar across languages, C++ requires the virtual keyword in base classes for overriding. Other languages, like Java, make all methods virtual by default, simplifying polymorphism without extra syntax.
8. What are the best use cases for function overloading in real-world applications?
Function overloading is best used when a function performs the same or similar operations on different types of input or with different numbers of parameters. Common examples include mathematical operations, logging functions, or utility functions like print() that need to handle various data types.
9. How does C++ handle ambiguity in function overloading?
C++ uses the function signature (name, parameter types, and parameter count) to distinguish overloaded functions. If the compiler cannot match an overloaded function uniquely, it results in a compilation error due to ambiguity.
10. Can you use function overriding and overloading together in C++?
Yes, both can coexist in C++. A derived class can override a base class function while also overloading that function within its scope, allowing flexibility in both inheritance and customization of function behavior.
11. What are some tools or IDEs that help manage and visualize class hierarchies in C++?
Popular IDEs like Visual Studio, CLion, and Eclipse offer tools for visualizing class hierarchies and managing complex relationships. Additionally, UML diagram tools like StarUML and Lucidchart are also helpful for C++ developers to visualize and document class structures and inheritance.
RELATED PROGRAMS