Inheritance is a cornerstone of object-oriented programming in C++. It allows a new class to be based on an existing class, inheriting its properties and behaviors. This powerful feature promotes code reuse and establishes a hierarchical relationship between classes.
To create a derived class in C++, use the following syntax:
class DerivedClass : access-specifier BaseClass {
// Derived class members
};
The access-specifier
can be public
, protected
, or private
, determining how the base class members are inherited.
C++ supports various types of inheritance:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!" << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Dog's own method
return 0;
}
In this example, Dog
inherits from Animal
, gaining access to the eat()
method.
The access specifier used in inheritance affects how base class members are accessible in the derived class:
public
: Public and protected members of the base class become public and protected members of the derived class, respectivelyprotected
: Public and protected members of the base class become protected members of the derived classprivate
: Public and protected members of the base class become private members of the derived classDerived classes can override functions inherited from the base class to provide their own implementation. This is crucial for achieving C++ Polymorphism.
class Animal {
public:
virtual void makeSound() {
cout << "The animal makes a sound" << endl;
}
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow!" << endl;
}
};
The override
keyword ensures that the function is indeed overriding a virtual function from the base class.
protected
members in base classes to allow derived classes access while maintaining encapsulationInheritance is a powerful feature in C++ that promotes code reuse and establishes relationships between classes. By understanding its principles and best practices, you can create more efficient and organized code structures. As you delve deeper into C++ programming, explore related concepts like C++ Polymorphism and C++ Abstract Classes to fully leverage the power of object-oriented programming.