C++ Inheritance - Basics and Usage


Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class by inheriting the properties and behaviors of an existing class. This promotes code reusability and the creation of more specialized classes. In this guide, we'll explore the basics of C++ inheritance and its usage.


Basic Inheritance

In C++, a class can inherit from another class using the class keyword followed by a colon and the public, protected, or private access specifier. Here's the basic syntax:


class DerivedClass : access_specifier BaseClass {
// Additional members and methods
};

Example:


#include <iostream>
using namespace std;
class Animal {
public:
void speak() {
cout << "Animal speaks." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks." << endl;
}
};
int main() {
Dog myDog;
myDog.speak();
myDog.bark();
return 0;
}

In this example, the Dog class inherits from the Animal class. The Dog class can access the speak method from the base class and has its own bark method.


Types of Inheritance

C++ supports different types of inheritance:


  • Single Inheritance: A derived class inherits from a single base class.
  • Multiple Inheritance: A derived class can inherit from multiple base classes.
  • Multilevel Inheritance: A class derives from a base class, which, in turn, derives from another base class.
  • Hierarchical Inheritance: Multiple classes derive from a single base class.
  • Hybrid Inheritance: A combination of different types of inheritance.

Access Control in Inheritance

Access specifiers (public, protected, private) define the level of access to the base class members in the derived class. The default is private.


Example of access control:


class Base {
private:
int privateData;
protected:
int protectedData;
public:
int publicData;
};
class Derived : public Base {
public:
void accessBaseMembers() {
// privateData is not accessible
protectedData = 10; // Accessible because it's protected
publicData = 20; // Accessible because it's public
}
};

Conclusion

C++ inheritance is a powerful mechanism for building complex class hierarchies and sharing code among classes. It enables you to create specialized classes and extend the functionality of existing classes. As you continue your C++ journey, you'll explore more advanced topics like virtual functions and polymorphism.