Table of Contents
- Introduction
- What is Function Overriding in C++?
- Why Do We Need Function Overriding in C++?
- Variations in Function Overriding
- 1. Call Overridden Function From Derived Class
- 2. Call Overridden Function Using Pointer
- 3. Access of Overridden Function to the Base Class
- 4. Access to Overridden Function
- Real-life Example
- A Problem to Solve
- Function Overloading Vs Function Overriding in C++
- The Pros and Cons of Using Function Overriding
- Key Takeaways
- Conclusion
- FAQs
Introduction
Welcome to the exciting world of function overriding in C++! Just like in a video game, where each character has its own special ability, function overriding allows us to give our classes unique behaviors that set them apart. In this article, we’ll explore why function overriding is essential for creating diverse and dynamic programs. We’ll understand what it is, how it works, and how we can use it to make our code more flexible and powerful. So, let’s dive in and unleash the full potential of function overriding in C++!
What is Function Overriding in C++?
A function is like a set of instructions that does a certain job when you give it some information. When you make a new version of a function in a special kind of way in C++, it’s called “function overriding”. This means you make a new version of a function in a class that already had it, but you keep the same name, what it gives back, and what you give it. This is useful when you want different classes to do the same job in their own way. It’s part of a thing called “Runtime Polymorphism”.
Syntax:
class Base {
public:
virtual void show() {
// base class code
}
};
class Derived : public Base {
public:
void show() {
// derived class code
}
};
Why Do We Need Function Overriding in C++?
Function overriding is important in C++ because it lets us customize how different classes do the same job. Imagine you have a base class with a function, and you want similar classes to do that function slightly differently. Instead of creating a new function in each class, you can use function overriding. This way, you keep the same function name, input, and output, but you can give each class its unique way of doing the job. It’s like giving different flavors to the same ice cream base. This helps organize your code and makes it more flexible.
Variations in Function Overriding
1. Call Overridden Function From Derived Class
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
virtual void display() {
cout << "This is a Shape." << endl;
}
};
// Derived class
class Circle : public Shape {
public:
void display() override {
cout << "This is a Circle." << endl;
}
};
int main() {
Shape* shapePtr; // Pointer to base class
Circle circleObj; // Derived class object
shapePtr = &circleObj; // Pointing to the derived class object
shapePtr->display(); // Calling overridden function from derived class
return 0;
}
Output:
This is a Circle.
Explanation:
- The code showcases a base class named
Shape
with a virtual function ‘display()
‘. - The derived class ‘
Circle
‘ overrides the ‘display()
‘ function from the base class. - In the ‘
main()
‘ function, an object ‘circleObj
‘ of the derived class ‘Circle
‘ is created. - A pointer ‘
shapePtr
‘ of the base class type is used to point to the ‘circleObj
‘ object. - The ‘
display()
‘ function is called using the ‘shapePtr
‘ pointer and it invokes the overridden function from the derived class. - The output of this program will be “This is a Circle.”
2. Call Overridden Function Using Pointer
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "This is the Base class" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "This is the Derived class" << endl;
}
};
int main() {
Base baseObj;
Derived derivedObj;
Base* ptr;
ptr = &baseObj; // Pointing to Base object
ptr->show(); // Calls Base class function
ptr = &derivedObj; // Pointing to Derived object
ptr->show(); // Calls Derived class function
return 0;
}
Output:
This is the Base class
This is the Derived class
Explanation:
- The code includes a Base class and a Derived class that inherits from the Base class.
- Both classes have a function named show().
- Objects of both classes, ‘
baseObj
‘ and ‘derivedObj
‘, are created. - A pointer of type Base* named ‘
ptr
‘ is used. - ‘
ptr
‘ is first pointed to the ‘baseObj
‘ object. - Calling ‘
ptr->show()
‘ invokes the show() function of the Base class. - ‘
ptr
‘ is then pointed to the ‘derivedObj
‘ object. - Calling ‘
ptr->show()
‘ now invokes the show() function of the Derived class. - This demonstrates function overriding, where the appropriate function is called based on the object being pointed to.
3. Access of Overridden Function to the Base Class
#include <iostream>
using namespace std;
class Base {
public:
void show() {
cout << "This is the Base class" << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << "This is the Derived class" << endl;
}
};
int main() {
Base b;
Derived d;
// Access overridden function using base class object
b.show(); // Output: "This is the Base class"
// Access overridden function using derived class object
d.show(); // Output: "This is the Derived class"
// Access overridden function using base class pointer
Base *ptr = &d;
ptr->show(); // Output: "This is the Derived class"
return 0;
}
Output:
This is the Base class
This is the Derived class
This is the Base class
Explanation:
- The code involves a base class called ‘
Base
‘ and a derived class named ‘Derived
‘. - Both classes have a function named ‘
show()
‘ which is overridden in the derived class. - In the ‘
main()
‘ function, instances of both classes are created. - The overridden function is accessed in three ways: using a base class object, a derived class object, and a base class pointer pointing to a derived class object.
- The output matches the comments provided in the code.
4. Access to Overridden Function
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "This is the Base class" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "This is the Derived class" << endl;
}
};
int main() {
Base* ptr;
Derived d;
ptr = &d; // Pointing to the Derived class object
// Accessing the overridden function through a pointer
ptr->show();
return 0;
}
Output:
This is the Derived class
Explanation:
- The code demonstrates inheritance in C++.
- It has a base class named ‘
Base
‘ and a derived class named ‘Derived
‘. - The ‘
show()
‘ function in the derived class overrides the same function in the base class. - In the ‘
main()
‘ function, a pointer of the base class type (ptr
) is used. - This pointer is assigned to an object of the derived class (
d
). - When the ‘
show()
‘ function is called using the pointer, and the overridden function in the derived class is invoked. - The output displayed will be “This is the Derived class”.
Real-life Example
Real-life Analogy: Baking a Cake
Imagine you’re learning how to bake from a family recipe book. The recipe book has a basic recipe for baking a plain vanilla cake which can be seen as our base or parent class. This basic recipe (function) tells you to just add flour, sugar, butter, and vanilla to bake the cake.
Now, let’s say you want to make it a bit special by adding chocolate to the cake. Instead of changing the original recipe in the book, you decide to add a twist to the method you learned (in your own style or version). Here, you’re essentially “overriding” the original cake baking method.
In C++ terms, the original recipe is like a function in the parent class. When you added your twist, you provided a new version of the same function in a child class, hence overriding the original.
Code Representation:
class VanillaCake {
public:
void recipe() {
cout << "Ingredients: Flour, Sugar, Butter, Vanilla" << endl;
}
};
class ChocolateVanillaCake : public VanillaCake {
public:
// Overriding the recipe function of the parent class
void recipe() {
cout << "Ingredients: Flour, Sugar, Butter, Vanilla, Chocolate" << endl;
}
};
int main() {
ChocolateVanillaCake myCake;
myCake.recipe(); // This will call the overridden function and print: "Ingredients: Flour, Sugar, Butter, Vanilla, Chocolate"
return 0;
}
Output:
Ingredients: Flour, Sugar, Butter, Vanilla, Chocolate
A Problem to Solve
Problem Statement:
You are developing a zoo management system, and your task is to model different kinds of birds in the system. All birds can make a sound, but each type of bird makes a different sound. You need to represent this using function overriding in C++.
- Create a Base Class ‘Bird’: This class should have a public method called
sound
that prints “This bird makes a sound.” - Create Derived Classes for Specific Birds: Create three derived classes
Parrot
,Crow
, andOwl
, all of which inherit from theBird
class. Each derived class should override thesound
method to print a specific sound for that type of bird.- Parrot: “Parrot says: Squawk!”
- Crow: “Crow says: Caw!”
- Owl: “Owl says: Hoot!”
- Demonstrate the Functionality: In your main function, create objects of the
Parrot
,Crow
, andOwl
classes and call theirsound
method to demonstrate that the correct sound is printed for each type of bird.
Expected Output:
Your program should produce the following output:
Parrot says: Squawk!
Crow says: Caw!
Owl says: Hoot!
Note:
Remember that function overriding requires the base class and derived class to have a method with the same name, return type, and parameter list. Make sure that the ‘sound
‘ method in the derived classes has the same signature as in the base class.
Function Overloading Vs Function Overriding in C++
Aspect | Function Overloading | Function Overriding |
---|---|---|
Definition | Multiple functions with the same name in the same scope but with different parameters. | Creating a function in the derived class with the same name, parameters, and return type as in the base class. |
Inheritance | Not related to inheritance. | Related to inheritance, occurs in the context of a base and derived class relationship. |
Return Type | Can have the same or different return types. | Must have the same return type. |
Arguments | Must have different parameter lists, including the number and/or types of parameters. | Must have the same parameter lists. |
Scope | Within the same class. | Involves a base and a derived class. |
Overload Resolution | Based on the number and types of arguments during a function call. | Based on the runtime object type during a function call using pointers or references. |
Overloaded Function Call | Decided at compile time based on the function arguments. | Decided at runtime based on the actual object type pointed to by pointers or references. |
Virtual Function | Not applicable, function overloading doesn’t involve virtual functions. | Requires the base class function to be virtual in order to enable function overriding. |
Example | int sum(int a, int b); double sum(double x, double y); | class Base { virtual void show(); }; class Derived : public Base { void show() override; }; |
The Pros and Cons of Using Function Overriding
Pros | Cons |
---|---|
Allows customization of behavior in subclasses | Can lead to complex code if overused |
Enables polymorphism and dynamic binding | Overriding a function by mistake can lead to unexpected results |
Promotes code reusability | Requires careful design and understanding of class hierarchies |
Facilitates efficient and organized code | Can be challenging to debug if errors occur |
Enhances flexibility in object-oriented design | May introduce performance overhead due to dynamic binding |
Key Takeaways
- Function Overriding: In C++, function overriding lets a subclass modify the behavior of a method inherited from its superclass.
- Superclass and Subclass: It occurs in a parent-child class relationship, where the subclass provides a new implementation for a method present in the superclass.
- Method Signature: The overridden method in the subclass must have the same name, parameters, and return type as the method in the superclass.
- Virtual Functions: For overriding, the method in the superclass should be declared as virtual. This allows the dynamic binding of the method call based on the actual object type at runtime.
- Runtime Polymorphism: Function overriding is a key component of runtime polymorphism, enabling different behaviors based on the actual object type being used.
Conclusion
In conclusion, mastering function overriding in C++ empowers you to prepare refined and adaptable programs. Through a solid understanding of this concept, you can create more refined and dynamic software solutions. Regular practice will boost your expertise in using function overriding effectively, improving your programming skills. Welcome the learning journey and watch yourself grow into a proficient practitioner of function overriding.
FAQs
What is function overriding in C++?
Function overriding in C++ is a feature of OOP that allows a subclass to provide a different implementation for a method already defined in its superclass.
Why do we use function overriding in C++?
We use function overriding in C++ to change the behavior of a method already defined in a parent class. It allows for polymorphism, making our programs more flexible and dynamic.
How do we use function overriding in C++?
We use function overriding in C++ by defining a method in the subclass with the same name, return type, and parameters as the one in the superclass.
Can using function overriding make code more confusing?
Yes, if not used correctly, function overriding can lead to confusion and errors. It’s important to understand how function overriding works and when to use it.
What are some examples of using function overriding in C++?
Some examples include overriding a display function, using a ‘virtual’ function in the base class, and using the ‘override’ keyword in the derived class.