Classes can be related in two ways: by inheritance and by composition. These are referred to as "is-a" vs "has-a" relationships. Inheritance is an "is-a" relationship and it is useful because it allows you to take functionality from an already existing class and reuse it without duplicating code. For example, if you have a class Animal
, you can create a class Dog
which *is a*n animal, and Dog
can inherit properties from Animal
. Animal
is known as the base class, and Dog
is known as the derived class. You can create many animals (cat, bird, etc) which can inherit from Animal
without having to recreate properies for each class.
Below is an example of the base class Animal
and the derived class Dog
, which inherits the members from Animal
.
The syntax to inherit from a class is
class derivedClassName : memberAccessModifier baseClassName
.
The memberAccessModifier
can bepublic
, private
, or protected
and it affects how the derived class inherits members of the base class. private
is default and means the derived class can't directly access the private members of the base class. public
means public members of the base class will be public in the derived class, and protected
means public and protected members of the base class will be protected in the derived class.
#include <iostream>
#include <string>
class Animal
{
private:
int mLegs;
std::string mName;
public:
Animal(int legs, std::string name)
{
mLegs = legs;
mName = name;
}
void printInfo()
{
std::cout << "My name is " << mName << " and I have " << mLegs << " legs.\n";
}
};
class Dog : public Animal
{
private:
std::string mMood;
public:
Dog(int legs, std::string name, std::string mood = "happy") : Animal(legs, name) {
mMood = mood;
}
void printInfo()
{
Animal::printInfo();
std::cout << "My mood is " << mMood << "!\n";
}
};
int main() {
Dog a(4, "Gremlin");
a.printInfo();
return 0;
}
// output
// My name is Gremlin and I have 4 legs.
// My mood is happy!
Notice the syntax for the Dog
constructor.
Dog(int legs, std::string name, std::string mood = "happy") : Animal(legs, name) {...}
Since the number of legs and name are set in the constructor, you need to specify which members will be set from the base class constructor.
You can also see how Dog
has a member variable mMood
, which the base class Animal
does not. printInfo
is also being overriden inside the Dog
class so that it can print info from the base class as well as the member variable (mMood
) that only it has. Inside the body of printInfo
in the Dog
class is a call to printInfo
in the base class: Animal::printInfo()
.
Further Reading/Viewing / References
- C++ Programming: Program Design Including Data Structures 8th ed. by D.S. Malik
- C++ OOP (2020) - What is inheritance in programming?
- Public, Protected and Private Inheritance in C++ Programming
- Difference Between Composition and Inheritance
Top comments (0)