C++ Inheritance Tutorial
Inheritance is a fundamental feature of Object-Oriented Programming (OOP) in C++. It allows one class (the derived class) to inherit attributes and behaviors (methods) from another class (the base class).
What is Inheritance?
Inheritance enables a class to acquire properties and behaviors from another class, promoting code reusability and method overriding.
#include <iostream>
using namespace std;
class Animal {
public:
void sound() {
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal { // Inherits from Animal
public:
void sound() {
cout << "Bark!" << endl;
}
};
int main() {
Dog dog;
dog.sound(); // Outputs: Bark!
return 0;
}
Types of Inheritance
There are several types of inheritance in C++:
- Single Inheritance: A class inherits from one base class.
- Multiple Inheritance: A class inherits from more than one base class.
- Multilevel Inheritance: A class inherits from a derived class which is itself derived from another class.
- Hierarchical Inheritance: Multiple classes inherit from a single base class.
- Hybrid Inheritance: A combination of two or more types of inheritance.
Constructor in Inheritance
In inheritance, constructors of the base class are called before the derived class's constructor.
class Animal {
public:
Animal() {
cout << "Animal created" << endl;
}
};
class Dog : public Animal {
public:
Dog() {
cout << "Dog created" << endl;
}
};
int main() {
Dog dog; // Outputs: Animal created, Dog created
return 0;
}
Access Specifiers in Inheritance
In inheritance, access to the base class members can be modified using access specifiers:
public: Members of the base class become accessible to the derived class and outside classes.protected: Members of the base class are accessible to the derived class, but not outside the class.private: Members are not accessible to the derived class.
class Base {
protected:
int x;
public:
Base() : x(10) {}
};
class Derived : public Base {
public:
void display() {
cout << "x = " << x << endl; // Accesses protected member
}
};
int main() {
Derived obj;
obj.display(); // Outputs: x = 10
return 0;
}
Polymorphism with Inheritance
Polymorphism allows methods in a base class to be overridden in derived classes, enabling dynamic method calls at runtime.
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Override base class function
cout << "Bark!" << endl;
}
};
int main() {
Animal* animal = new Dog(); // Base class pointer to derived class object
animal->sound(); // Outputs: Bark!
delete animal;
return 0;
}