C++ inheritance
Created By: chatGPT
In C++, inheritance is a fundamental feature that allows a class (called the derived class) to inherit the properties and behaviors (member variables and functions) from another class (called the base class). This promotes code reusability and establishes a relationship between classes.There are several types of inheritance in C++, including single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance, and hybrid inheritance.Here’s a simple example showcasing single inheritance:In C++, we also want to be aware of access specifiers when inheriting classes. The three access specifiers are public, protected, and private. The default mode of inheritance is private if not specified, and public inheritance maintains the public/protected status of the base class.In summary, inheritance in C++ enables a structured approach to building class hierarchies while promoting code reuse and maintaining the principles of encapsulation and polymorphism. Understanding how to effectively implement inheritance is crucial for creating well-architected applications.
First, we define a base class called
Animal
:class Animal {
public:
void speak() {
std::cout << "Animal speaks" << std::endl;
}
};
Next, we create a derived class called
Dog
that inherits from Animal
:class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks" << std::endl;
}
};
Now we can utilize both
speak
from the base class and bark
from the derived class:int main() {
Dog myDog;
myDog.speak(); // Inherited function
myDog.bark(); // Dog's own function
return 0;
}
This will output:
- Animal speaks
- Dog barks
In this example, Dog
inherits the speak
method from Animal
, demonstrating how inheritance allows the derived class to leverage the functionality of the base class.
For instance, if you change the inheritance of Dog
to private:
class Dog : private Animal { ... }
Now, speak
is not accessible from Dog
objects outside this class, demonstrating a more restricted access to the base class members.