Welcome to this tutorial on understanding inheritance and polymorphism in C++. Our goal is to give you a solid understanding of these two fundamental concepts in object-oriented programming.
You will learn:
Prerequisites:
Inheritance is a feature of object-oriented programming that allows a class (child or derived class) to inherit properties and methods from another class (parent or base class). It promotes code reusability and hierarchy of classes.
Let's consider an example:
class Animal { // Parent class
public:
void eat() {
cout << "I can eat!" << endl;
}
};
class Dog : public Animal { // Child class
public:
void bark() {
cout << "I can bark!" << endl;
}
};
In the above code, Dog
is a derived class that inherits from the Animal
base class. Therefore, an object of the Dog
class can access the eat()
method.
Polymorphism is another feature of object-oriented programming that allows one function to behave differently based on the object that calls it. It provides flexibility while designing large functional units.
Here's an example:
class Animal {
public:
virtual void sound() {
cout << "Animals can make sound!" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks!" << endl;
}
};
In the above code, sound()
in the Dog
class overrides the sound()
in the Animal
class. This is an example of polymorphism.
Let's look at some more practical examples:
class Animal { // Base class
public:
void eat() {
cout << "I can eat!" << endl;
}
};
class Dog : public Animal { // Derived class
public:
void bark() {
cout << "I can bark!" << endl;
}
};
int main() {
Dog dog1;
dog1.eat(); // Accessing method of parent class
dog1.bark(); // Accessing method of child class
return 0;
}
Expected output:
I can eat!
I can bark!
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animals can make sound!" << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Overriding function
cout << "Dog barks!" << endl;
}
};
int main() {
Animal* baseptr; // Base class pointer
Dog dog1;
baseptr = &dog1;
baseptr->sound(); // Late binding occurs
return 0;
}
Expected output:
Dog barks!
We have covered the following topics:
Next steps for learning:
Create a base class Vehicle
and derived classes Car
and Bike
with some properties and methods.
Implement polymorphism with a base class Shape
and derived classes Circle
and Rectangle
. Each class should have a method area()
that calculates and prints the area.
Solutions and explanations will be provided upon request.
These exercises will help you gain a practical understanding of inheritance and polymorphism in C++. Continue practicing to solidify the concepts.