ITP

BCA - OOPS and Data Structures

What is Inheritance ? Explain in Details

In : BCA Subject : OOPS and Data Structures

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) . It allows a class (called a child  or derived class ) to inherit properties and behaviors  (like variables and functions) from another class (called a parent  or base class ).

Types of Inheritance:

  1. Single - One class inherits from one parent
  2. Multiple - One class inherits from multiple parents
  3. Multilevel - A class inherits from a class that itself inherits from another
  4. Hierarchical - Multiple classes inherit from one parent
  5. Hybrid - Combination of two or more types above

Inheritance:

  • Allows a class to inherit properties and methods from another class.
  • Promotes code reuse , modularity , and organization .

Example :

#include
using namespace std;

// Base class
class Person {
protected:
    string name;
public:
    void setName(string n) {
        name = n;
    }

    void printName() {
        cout << "Name: " << name << endl;
    }
};

// Derived class
class Student : public Person {
private:
    int rollNo;
public:
    void setRoll(int r) {
        rollNo = r;
    }

    void printDetails() {
        printName();  // inherited function
        cout << "Roll No: " << rollNo << endl;
    }
};

int main() {
    Student s1;
    s1.setName("itprashnavali");
    s1.setRoll(101);
    s1.printDetails();

    return 0;
}

 

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap