DEV Community

Cover image for What is Inheritance in OOP? Explained in Simple Words
Aliza Kanwal
Aliza Kanwal

Posted on

What is Inheritance in OOP? Explained in Simple Words

Inheritance means ek Class ko doosri Class ki cheezain mil jati hain.

Jaise bachay ko apne Maa Baap se cheezain milti hain, waise hi Child Class ko Parent Class se properties milti hain.

Example: Person ek Parent Class hai. Student ek Child Class hai. Student ko Person ki har cheez milegi, plus uski apni bhi hogi.


cpp
#include<iostream>
using namespace std;

// Parent Class
class Person {
public:
    string name;
    int age;

    void introduce() {
        cout << "My name is " << name << endl;
        cout << "My age is " << age << endl;
    }
};

// Child Class - Person se Inheritance le rahi hai
class Student : public Person {
public:
    int rollNo;

    void showRollNo() {
        cout << "My Roll No is " << rollNo << endl;
    }
};

int main() {
    Student s1;
    s1.name = "Aliza";
    s1.age = 20;
    s1.rollNo = 1;

    s1.introduce();
    s1.showRollNo();

    return 0;
}
Output:
My name is Aliza
My age is 20
My Roll No is 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)