C++ Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a class (called the derived class) to acquire properties and behaviors of another class (called the base class). Inheritance promotes code reusability and establishes a relationship between classes.
Types of Inheritance
- The derived class inherits all accessible members (public and protected) of the base class.
- Private members of the base class are not directly accessible in the derived class.
- Access specifiers (public, protected, private) control the visibility of base class members in the derived class.
Next Topic
Next, learn about Polymorphism in C++.
- Single Inheritance: A derived class inherits from a single base class.
- Multiple Inheritance: A derived class inherits from more than one base class.
- Multilevel Inheritance: A chain of inheritance where a class is derived from a derived class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
- Hybrid Inheritance: Combination of two or more types of inheritance.
Syntax
class BaseClass {
// Base class members
};
class DerivedClass : access_specifier BaseClass {
// Derived class members
};
Example: Single Inheritance
#include <iostream>
using namespace std;
// Base class
class Person {
public:
string name;
void displayName() {
cout << "Name: " << name << endl;
}
};
// Derived class
class Student : public Person {
public:
int rollNo;
void displayRollNo() {
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s1;
s1.name = "Alice"; // Inherited from Person
s1.rollNo = 101;
s1.displayName();
s1.displayRollNo();
return 0;
}
Output
Name: Alice Roll No: 101
Important Notes
- The derived class inherits all accessible members (public and protected) of the base class.
- Private members of the base class are not directly accessible in the derived class.
- Access specifiers (public, protected, private) control the visibility of base class members in the derived class.
Next Topic
Next, learn about Polymorphism in C++.