Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (derived class) to inherit properties and behaviors (methods) from another class (base class). This promotes code reusability and establishes a hierarchical relationship between classes. In this article, we will discuss three practical examples of inheritance in C++, illustrating how base and derived classes work together.
In this example, we create a base class called Animal and derived classes Dog and Cat. This demonstrates how different animals can share common properties and behaviors.
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
void eat() {
cout << "This animal eats food." << endl;
}
};
// Derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "Woof! Woof!" << endl;
}
};
// Derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "Meow! Meow!" << endl;
}
};
int main() {
Dog dog;
Cat cat;
dog.eat();
dog.bark();
cat.eat();
cat.meow();
return 0;
}
Animal class contains a method eat(), which is inherited by both Dog and Cat classes.bark() for Dog and meow() for Cat).This example extends the previous one by adding constructors to the base and derived classes. This shows how to initialize properties for both base and derived classes.
#include <iostream>
using namespace std;
// Base class
class Animal {
protected:
string name;
public:
Animal(string animalName) : name(animalName) {}
void eat() {
cout << name << " eats food." << endl;
}
};
// Derived class
class Dog : public Animal {
public:
Dog(string dogName) : Animal(dogName) {}
void bark() {
cout << name << " says Woof!" << endl;
}
};
int main() {
Dog dog("Buddy");
dog.eat();
dog.bark();
return 0;
}
Animal constructor initializes the name property.Dog class constructor calls the base class constructor to set the name.This example demonstrates multi-level inheritance by adding another derived class, Puppy, which inherits from Dog. This illustrates a more complex relationship among classes.
#include <iostream>
using namespace std;
// Base class
class Animal {
protected:
string name;
public:
Animal(string animalName) : name(animalName) {}
void eat() {
cout << name << " eats food." << endl;
}
};
// First derived class
class Dog : public Animal {
public:
Dog(string dogName) : Animal(dogName) {}
void bark() {
cout << name << " says Woof!" << endl;
}
};
// Second derived class
class Puppy : public Dog {
public:
Puppy(string puppyName) : Dog(puppyName) {}
void play() {
cout << name << " is playing." << endl;
}
};
int main() {
Puppy puppy("Charlie");
puppy.eat();
puppy.bark();
puppy.play();
return 0;
}
Puppy class inherits from the Dog class, thus gaining access to its methods.