Logo
Unit 12 – Inheritance in C++

Inheritance in C++

Duration: 5 minutes

Introduction

Hello Coders! Welcome to the realm of Inheritance in C++, a powerful concept that forms the backbone of object-oriented programming. Inheritance allows you to create a hierarchy of classes, fostering code reuse and structuring programs in a more intuitive and efficient way.

Understanding Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that enables a new class (subclass/derived class) to inherit the properties and behaviors of an existing class (superclass/base class). This promotes code reuse and the creation of a hierarchy of classes.

Here’s a basic example demonstrating single inheritance:

#include <iostream>
#include <iostream>
// Base class
class Animal {
public:
Animal(const std::string& n) : name(n) {}
void eat() {
std::cout << name << " is eating." << std::endl;
}
void sleep() {
std::cout << name << " is sleeping." << std::endl;
}
private:
std::string name;
};
// Derived class
class Dog : public Animal {
public:
Dog(const std::string& n, const std::string& b) : Animal(n), breed(b) {}
void bark() {
std::cout << "Woof! Woof!" << std::endl;
}
private:
std::string breed;
};
int main() {
// Create a Dog object
Dog myDog("Buddy", "Golden Retriever");
// Access base class methods
myDog.eat();
myDog.sleep();
// Access derived class method
myDog.bark();
return 0;
}

In this example, Dog is derived from Animal. The Dog class inherits the eat and sleep methods from the base class Animal and adds its own method bark.

Assignment: Implement Inheritance in a Class Hierarchy

With the above example:-

Experiment with different access specifiers (public, protected, private) for the base class members. Observe how these changes affect the accessibility of inherited members in derived classes.

  • Transform the Animal class into an abstract base class by declaring a pure virtual function, e.g., virtual void makeSound() = 0;. Ensure that derived classes provide an implementation for this function.

Conclusion

Feel free to modify the class hierarchy, creating additional derived classes or adding new methods. This exercise will provide hands-on experience with inheritance in C++.

A thorough understanding of inheritance in C++ equips you with the tools to build scalable, organized, and efficient software systems. Happy coding!

Next Tutorial: Polymorphism in C++

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!