Inheritance In CPP

Inheritance is a powerful concept in object-oriented programming (OOP) that allows us to reuse code and create more complex and sophisticated classes.

Inheritance is a mechanism of inheriting the property from parent class object to child class object.The class that inherits the properties and behaviors is called the derived class or child class, and the class that is being inherited from is called the base class or parent class.

what is property- Variables and functions with in a class is know as properties of that class.




Some Other Names for class relationship:
Parent Classsuper classBase class
Child classSub classDerived class


Syntex for Inheritance :

class DerivedClassName : VisibilityMode  BaseClassName
{
// Members of the derived class
}

DerivedClassName is the name of the derived class, BaseClassName is the name of the base class, and VisibilityMode specifies the access level of the inherited members (public, protected, or private).


Like:
class d : public b
{ // Members of the derived class.
};

The above code defines a class called "d" that is derived from (or inherits from) another class called "b" using public inheritance.

When a class is derived from another class using public inheritance, it means that the derived class "d" will inherit all the public and protected members (attributes and methods) of the base class "b". This allows the derived class to reuse the code and functionality defined in the base class.

Inside the class "d", you can define additional members specific to the derived class. These members will be unique to class "d" and will not be inherited by other classes.

By using public inheritance, the derived class "d" can access the public members of the base class "b" directly. Protected members are also accessible within the derived class and any other classes derived from "d". Private members of the base class are not directly accessible in the derived class.

Overall, this code establishes an "is-a" relationship between the derived class "d" and the base class "b", allowing "d" to inherit and extend the functionality of "b".

Example:

#include <iostream>
using namespace std;

class Animal {
protected:
string name;
      
public:
void setName(string n) {
name = n;
}
};


class Dog : public Animal {
public:
void bark() {
 cout << "The dog named " << name << " is barking." << endl;
}
};


int main(){
   Dog dog;
   dog.setName("Tuffy");
   dog.bark();
}
Output:
The dog named Tuffy is barking.

In this example, the Dog class inherits from the Animal class. The Animal class has a protected member name and a public method setName(). The Dog class adds its own method bark() and can access the inherited member name to bark.


Roll Of Visibility Mode In Inheritance


Inheritance is a fundamental concept in object-oriented programming (OOP) where a class can inherit properties and methods from another class. In OOP language, visibility mode refers to the accessibility of inherited members (attributes and methods) in the derived class.


Visibility Modes:


  1. Public: In this mode, the inherited members are accessible both within the derived class and from outside the class.

    In C++, the syntax for implementing public visibility mode in inheritance is as follows:

            class DerivedClass : public BaseClass {
                // Class members and functions
            };
        
  2. Protected: With the protected mode, the inherited members are accessible within the derived class itself and its subclasses.

    In C++, the syntax for implementing protected visibility mode in inheritance is as follows:

        class DerivedClass : protected BaseClass {
        // Class members and functions
    };
        
  3. Private: In this mode, the inherited members are not directly accessible in the derived class. They can only be accessed by the base class itself.

    In C++, the syntax for implementing private visibility mode in inheritance is as follows:

        class DerivedClass : private BaseClass {
        // Class members and functions
        };
        

The visibility mode determines the level of encapsulation and access control for inherited members. It allows for controlling the visibility of data and methods, providing a way to enforce encapsulation and data hiding principles in OOP. By using the appropriate visibility mode, you can restrict or expose certain functionality and data to ensure proper usage and maintain the integrity of the classes in your program.



C++ Visibility Modes and Access Specifiers

Visibility Mode Access Specifier Accessibility in Derived Class
Public Inheritance public Remains public
protected Remains protected
private Not accessible
Protected Inheritance public Protected
protected Protected
private Not accessible
Private Inheritance public Private
protected Private
private Not accessible


Types of Inheritance:



  • Single Inheritance: A derived class inherits from a single base class.
    BaseClass DerivedClass
  • Multiple Inheritance: A derived class inherits from multiple base classes.
    BaseClass1 BaseClass2 DerivedClass
  • Multilevel Inheritance: A derived class becomes the base class for another derived class.
    Grand parent Parent Derived
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
    Vehicle Car Truck Sedan SUV Pickup 18-Wheeler
  • Hybrid Inheritance: A combination of multiple and hierarchical inheritance.
    Base Derived 1 Derived 2 Sub-Derived Grandparent Parent 1 Parent 2 Derived


Single Inheritance :


Single inheritance is a type of inheritance in object-oriented programming where a class inherits from only one base class. In single inheritance, a derived class (also known as a subclass or child class) can have only one immediate base class (also known as a superclass or parent class).

With single inheritance, a derived class inherits all the non-private members (data members and member functions) of its base class, which allows for the reuse of code and the extension of functionality in a structured manner. The derived class can also add its own members and override or extend the behavior of the inherited members.

Here's a simple example to illustrate single inheritance:

#include<iostream>
using namespace std;

class Student  // Base Class
{
   int roll;
   char name[25];
   public :
   void getData()
   {
     cout<<"Enter roll number :"<<endl;
     cin>>roll;
     cout<<"Enter the name :"<<endl;
     cin>>name;
   }

    void displayData()
    {
      cout<<"Roll No :"<<roll<<endl;
      cout<<"Name : "<<name<<endl;
    }
};


 

class Marks :public  Student  // Derived Class
 {
   int hindi,english,math,science,music;
   public :
   void readData(); // declaration
   void putData(); // declaration

 };

void Marks::readData() // definition
{
      this ->getData();
      cout<<"Enter the marks of Hindi: "<<endl;
      cin>> hindi;
      cout<<"Enter the marks of English: "<<endl;
      cin>>english;
      cout<<"Enter the marks of Math: "<<endl;
      cin>>math;
      cout<<"Enter the marks of Science: "<<endl;
      cin>>science;
      cout<<"Enter the marks of Music: "<<endl;
      cin>>music;
}

void Marks ::putData() // definition
{
      displayData();
      cout<<"Marks in Hindi: "<<hindi<<endl;
      cout<<"Marks in English: "<<english<<endl;
      cout<<"Marks in Math: "<<math<<endl;
      cout<<"Marks in Science: "<<science<<endl;
      cout<<"Marks in Music: "<<music<<endl;
}


int main()
{
     Marks obj; // object of derived class
     obj.readData();
     obj.putData();
}
    
Output:
Enter roll number :
101
Enter the name :
Ram
Enter the marks of Hindi:
99
Enter the marks of English:
98
Enter the marks of Math:
89
Enter the marks of Science:
97
Enter the marks of Music:
96
Roll No :101
Name : Ram
Marks in Hindi: 99
Marks in English: 98
Marks in Math: 89
Marks in Science: 97
Marks in Music: 96  


Single inheritance example with public access modifier and public accessiblity mode in cpp

In C++, when a member variable or function is declared with the public access modifier, it means that it can be accessed by any code that has access to the derived class. The public accessibility mode in inheritance allows the derived class to inherit the public and protected members of the base class as public members in the derived class.

#include <iostream>

class Shape {  // Base class
public: //public access modifier
double area;

void displayArea() {
std::cout << "Area: " << area << std::endl;
}
};


// Derived class
class Rectangle : public Shape {
public:
double width;
double height;

void calculateArea() {
area = width * height;
}
};


int main() {
Rectangle rect;
rect.width = 5.0;
rect.height = 3.0;

rect.calculateArea();
rect.displayArea();

return 0;
}

In this example, we have a base class called Shape with a public member variable area and a public member function displayArea(). We also have a derived class called Rectangle that inherits from Shape using the public accessibility mode.

The Rectangle class adds two additional public member variables, width and height, and a public member function called calculateArea(). This function calculates the area of the rectangle and assigns it to the area member variable inherited from the base class.

In the main() function, we create an object of the Rectangle class called rect. We set the values of width and height to 5.0 and 3.0, respectively. Then we call the calculateArea() function to calculate the area of the rectangle and display it using the displayArea() function inherited from the base class.

Output:
Area: 15

As you can see, the derived class Rectangle can access and modify the public member variable area inherited from the base class Shape. It can also access the public member function displayArea(). This demonstrates the inheritance of public members with public accessibility mode in C++.



Single inheritance example with protected access modifier and public accessibility mode in cpp

In C++, when a member variable or function is declared with the protected access modifier, it means that it can only be accessed within the class itself and its derived classes. The public accessibility mode in inheritance allows the derived class to inherit the protected members of the base class as protected members in the derived class.


Here's an example to illustrate this:

#include <iostream>

class Shape {   // Base class
protected: //protected access modifier
    double area;
    
public:
    void displayArea() {
        std::cout << "Area: " << area << std::endl;
    }
};


// Derived class
class Rectangle : public Shape {
public:
    double width;
    double height;
    
    void calculateArea() {
        area = width * height;
    }
};


int main() {
    Rectangle rect;
    rect.width = 5.0;
    rect.height = 3.0;
    
    rect.calculateArea();
    rect.displayArea();
    
    return 0;
}

In this example, we have a base class called Shape with a protected member variable area and a public member function displayArea(). We also have a derived class called Rectangle that inherits from Shape using the public accessibility mode.

The Rectangle class adds two additional public member variables, width and height, and a public member function called calculateArea(). This function calculates the area of the rectangle and assigns it to the area member variable inherited from the base class.

In the main() function, we create an object of the Rectangle class called rect. We set the values of width and height to 5.0 and 3.0, respectively. Then we call the calculateArea() function to calculate the area of the rectangle and display it using the displayArea() function inherited from the base class.

Output:
Area: 15

As you can see, the derived class Rectangle can access and modify the protected member variable area inherited from the base class Shape. It can also access the public member function displayArea(). This demonstrates the inheritance of protected members with public accessibility mode in C++.



Single inheritance example with private access modifier and public accessibility mode in cpp

In C++, when a member variable or function is declared with the private access modifier, it means that it can only be accessed within the class itself and is not accessible to derived classes. Therefore, when using the public accessibility mode in inheritance, the private members of the base class are not inherited by the derived class.

Here's an example to illustrate this:

#include <iostream>

class Shape {   // Base class
private: //private access modifier
    double area;
    
public:
    void displayArea() {
        std::cout << "Area: " << area << std::endl;
    }
};



class Rectangle : public Shape {  // Derived class
public:
    double width;
    double height;
    
    void calculateArea() {
        // Cannot access the 'area' member variable here
        // area = width * height; // Error: 'area' is inaccessible
    }
};
 
 
int main() {
    Rectangle rect;
    rect.width = 5.0;
    rect.height = 3.0;
    
    // rect.calculateArea(); // Error: 'calculateArea' is inaccessible
    // rect.displayArea(); // Error: 'displayArea' is inaccessible
    
    return 0;
}

In this example, we have a base class called Shape with a private member variable area and a public member function displayArea(). We also have a derived class called Rectangle that inherits from Shape using the public accessibility mode.

The Rectangle class adds two additional public member variables, width and height, but it cannot access or modify the private member variable area inherited from the base class.

In the main() function, when we try to access the calculateArea() and displayArea() functions from the Rectangle class, or access the area member variable, we get compilation errors because they are inaccessible due to their private visibility in the base class.

To summarize, when using the public accessibility mode in inheritance, private members of the base class are not inherited and cannot be accessed by the derived class. Only public and protected members of the base class are inherited as protected members in the derived class.



Here's an example in C++ that demonstrates the use of private and protected access modifier and private, protected, public accessibility mode in inheritance:

#include <iostream>

class Base {   // Base class
private:
    int privateData;

protected:
    int protectedData;

public:
    Base() {
        privateData = 10;
        protectedData = 20;
    }
};



// Derived class inheriting privately
class DerivedPrivate : private Base {
public:
    void displayData() {
        // Accessing private data member from the base class is not allowed
        // std::cout << privateData << std::endl; // Error: 'privateData' is a private member of 'Base'

        // Accessing protected data member from the base class is allowed
        std::cout << protectedData << std::endl;
    }
};



// Derived class inheriting protectedly
class DerivedProtected : protected Base {
public:
    void displayData() {
        // Accessing private data member from the base class is not allowed
        // std::cout << privateData << std::endl; // Error: 'privateData' is a private member of 'Base'

        // Accessing protected data member from the base class is allowed
        std::cout << protectedData << std::endl;
    }
};


// Derived class inheriting publicly
class DerivedPublic : public Base {
public:
    void displayData() {
        // Accessing private data member from the base class is not allowed
        // std::cout << privateData << std::endl; // Error: 'privateData' is a private member of 'Base'

        // Accessing protected data member from the base class is allowed
        std::cout << protectedData << std::endl;
    }
};


int main() {
    DerivedPrivate derivedPrivate;
    derivedPrivate.displayData(); // Output: 20

    DerivedProtected derivedProtected;
    derivedProtected.displayData(); // Output: 20

    DerivedPublic derivedPublic;
    derivedPublic.displayData(); // Output: 20

    return 0;
}

Output:
20
20
20

In this example, we have a Base class with a private data member privateData and a protected data member protectedData.

The DerivedPrivate class inherits privately from Base, which means that both the private and protected members of Base become private members of DerivedPrivate. Therefore, DerivedPrivate can access the protected data member protectedData directly, but not the private data member privateData.

The DerivedProtected class inherits protectedly from Base, which means that both the private and protected members of Base become protected members of DerivedProtected. Consequently, DerivedProtected can access both the private and protected data members of Base within its member functions.

The DerivedPublic class inherits publicly from Base, which means that the protected data member protectedData becomes protected in DerivedPublic, and the private data member privateData remains inaccessible.

In the main function, we create objects of each derived class and call the displayData function to demonstrate the accessibility of the inherited members.



Another example for Single Inheritance. Marks is treated as parent class and Student as a child class. In this program we use setter and getter methods for data member to read and write the value.

#include <iostream>
#include <string>

using namespace std;

class Marks {
private:
    int hindi;
    int english;
    int math;
    int science;
    int socialScience;
    int game;

public:
    // Constructor
    Marks(int h, int e, int m, int sci, int ss, int g)
        : hindi(h), english(e), math(m), science(sci), socialScience(ss), game(g) {}

    // Setter methods
    void setHindi(int h) {
        hindi = h;
    }

    void setEnglish(int e) {
        english = e;
    }

    void setMath(int m) {
        math = m;
    }

    void setScience(int sci) {
        science = sci;
    }

    void setSocialScience(int ss) {
        socialScience = ss;
    }

    void setGame(int g) {
        game = g;
    }

    // Getter methods
    int getHindi() const {
        return hindi;
    }

    int getEnglish() const {
        return english;
    }

    int getMath() const {
        return math;
    }

    int getScience() const {
        return science;
    }

    int getSocialScience() const {
        return socialScience;
    }

    int getGame() const {
        return game;
    }
};

class Student : public Marks {
private:
    int roll;
    string firstName;
    string lastName;
    int age;

public:
    // Constructor
    Student(int r, const string& fn, const string& ln, int a, int h, int e, int m, int sci, int ss, int g)
        : Marks(h, e, m, sci, ss, g), roll(r), firstName(fn), lastName(ln), age(a) {}

    // Getter methods for Student class
    int getRoll() const {
        return roll;
    }

    const string& getFirstName() const {
        return firstName;
    }

    const string& getLastName() const {
        return lastName;
    }

    int getAge() const {
        return age;
    }
};

int main() {
    // Creating an object of the Student class
    Student student(101, "John", "Doe", 18, 90, 85, 92, 88, 95,10);

    // Displaying student information and marks using getter methods
    cout << "Roll Number: " << student.getRoll() << endl;
    cout << "Name: " << student.getFirstName() << " " << student.getLastName() << endl;
    cout << "Age: " << student.getAge() << endl;
    cout << "Hindi: " << student.getHindi() << endl;
    cout << "English: " << student.getEnglish() << endl;
    cout << "Math: " << student.getMath() << endl;
    cout << "Science: " << student.getScience() << endl;
    cout << "Social Science: " << student.getSocialScience() << endl;
    cout << "Game: " << student.getGame() << endl;

    return 0;
}

Output:
Roll Number: 101
Name: John Doe
Age: 18
Hindi: 90
English: 85
Math: 92
Science: 88
Social Science: 95
Game: 10


Multi-level inheritance


Multi-level inheritance is a type of inheritance in object-oriented programming where a class inherits from another class, which, in turn, inherits from yet another class. This creates a chain or hierarchy of classes, where each derived class (child class) inherits properties and behaviors from its immediate base class (parent class), and indirectly, from all the ancestor classes in the chain.

In multi-level inheritance, a class can have only one immediate base class, but it can inherit features from multiple ancestor classes through the chain of inheritance. It allows for the reusability of code and promotes the concept of creating specialized classes that inherit from more general classes, leading to a structured and organized class hierarchy.

Here's a simple example to illustrate multi-level inheritance:

#include<iostream>
using namespace std;

// Base Class
class Student
{
   protected:
   int roll;
   char name[25];
   public :
   void getData()
   {
     cout<<"Enter roll number :"<<endl;
     cin>>roll;
     cout<<"Enter the name :"<<endl;
     cin>>name;
   }

    void display()
    {
      cout<<"Roll No :"<<roll<<endl;
      cout<<"Name : "<<name<<endl;
    }
};

// Drived Class

class Marks :protected  Student // Single Inheritance
{
  protected:
  int subjects[6];
  public :
  void readdata(); // declaration
  void putdata(); // declaration

};

void Marks::readdata() // definition
   {
     this ->getData();

     cout<<"Enter the marks of Hindi "<<endl;
     cin>>subjects[0];
     cout<<"Enter the marks of English "<<endl;
     cin>>subjects[1];
     cout<<"Enter the marks of Math "<<endl;
     cin>>subjects[2];
     cout<<"Enter the marks of Science "<<endl;
     cin>>subjects[3];
     cout<<"Enter the marks of SS "<<endl;
     cin>>subjects[4];
     cout<<"Enter the marks of Games "<<endl;
     cin>>subjects[5];

  }
  
  void Marks ::putdata() // definition
  {
     cout<<endl<<"Record of a Student is :"<<endl;
     display();
     cout<<"The marks In Hindi :";
     cout<<subjects[0]<<endl;
     cout<<"The marks In English ";
     cout<<subjects[1]<<endl;
     cout<<"The marks In Math ";
     cout<<subjects[2]<<endl;
     cout<<"The marks Science Science ";
     cout<<subjects[3]<<endl;
     cout<<"The marks In SS ";
     cout<<subjects[4]<<endl;
     cout<<"The marks In Games ";
     cout<<subjects[5]<<endl;
   }
   
  class Result : private Marks // Multi Level Inheritance
   {
    int obtaind_marks=0; 
    public:
    void InsertRecord()
    {
    this ->readdata();
    }
    void result()
    {
    for(int i=0;i<6;i++)
    {
    obtaind_marks +=subjects[i];
    }
    cout<<endl<<endl<<"-------------------------"<<endl;
    cout<<"Roll No is:"<<roll<<endl;
    cout<<"Name is :" <<name<<endl;
    cout<<"Total Marks : "<<obtaind_marks<<endl;
    }
   };

int main()
  {
  Result obj;
  obj.InsertRecord();
  obj.result();
  }
Enter roll number :
101
Enter the name :
Ram
Enter the marks of Hindi
99
Enter the marks of English
98
Enter the marks of Math
96
Enter the marks of Science
86
Enter the marks of SS
94
Enter the marks of Games
95


-------------------------
Roll No is:101
Name is :Ram
Total Marks : 568


Multiple inheritance


Multiple inheritance is a concept in object-oriented programming (OOP) where a class can inherit properties and behaviors from more than one base class. In other words, a class can have multiple parent classes from which it inherits features. This allows a derived class to combine the characteristics of multiple base classes.


Here's a simple example to illustrate Multiple inheritance:

 #include<iostream>
 using namespace std;

 // Base Class
 class Student
 {
   protected:
   int roll;
   char name[25];
   public :
   void getData()
   {
     cout<<"Enter roll number :"<<endl;
     cin>>roll;
     cout<<"Enter the name :"<<endl;
     cin>>name;
   }

    void display()
    {
      cout<<"Roll No :"<<roll<<endl;
      cout<<"Name : "<<name<<endl;
    }
 };

 class Subject 
 {
   protected:
   int subjects[6];
   public :
   void readdata(); // declaration
   void putdata(); // declaration

 };

   void Subject::readdata() // definition
   {
      cout<<"Enter the marks of Hindi "<<endl;
      cin>>subjects[0];
      cout<<"Enter the marks of English "<<endl;
      cin>>subjects[1];
      cout<<"Enter the marks of Math "<<endl;
      cin>>subjects[2];
      cout<<"Enter the marks of Science "<<endl;
      cin>>subjects[3];
      cout<<"Enter the marks of SS "<<endl;
      cin>>subjects[4];
      cout<<"Enter the marks of Games "<<endl;
      cin>>subjects[5];

   }

   void Subject ::putdata() // definition
   {
      cout<<endl<<"Record of a Student is :"<<endl;
      cout<<"The marks In Hindi :";
      cout<<subjects[0]<<endl;
      cout<<"The marks In English ";
      cout<<subjects[1]<<endl;
      cout<<"The marks In Math ";
      cout<<subjects[2]<<endl;
      cout<<"The marks Science Science ";
      cout<<subjects[3]<<endl;
      cout<<"The marks In SS ";
      cout<<subjects[4]<<endl;
      cout<<"The marks In Games ";
      cout<<subjects[5]<<endl;
   }

   class Game
   {
      char game[45];
      public:
      void getGame()
      {
       cout<<"Which Game Do you Like :"<<endl;
       cin>>game;
      }

      void showGame()
      {
         cout<<"Game is : "<<game<<endl;
      }

   };

   class Result :private Student, private Subject, private Game // Multiple Inheritance
   {
      int obtaind_marks=0; // must assign with a value 0. otherwise will give garbage.
      public:
      void InsertRecord()
      {
      	getData();
        readdata();
        getGame();
      }
      void result()
      {
         for(int i=0;i<6;i++)
         {
           obtaind_marks +=subjects[i];
         }
         cout<<endl<<"Output is :"<<endl;
         display();
        cout<<"Result is : "<<obtaind_marks<<endl;
         showGame();
      }
   };

   int main()
   {
     Result obj;
     obj.InsertRecord();
     obj.result();
    }
Output:
Enter roll number :
101
Enter the name :
Ram
Enter the marks of Hindi
98
Enter the marks of English
89
Enter the marks of Math
96
Enter the marks of Science
69
Enter the marks of SS
79
Enter the marks of Games
97
Which Game Do you Like :
Cricket

Output is :
Roll No :101
Name : Ram
Result is : 528
Game is : Cricket


Hierarchical inheritance


Hierarchical inheritance is a type of inheritance in object-oriented programming (OOP) where a single base class is inherited by multiple derived classes. In other words, it involves the creation of a class hierarchy where multiple classes are derived from the same base class.

In hierarchical inheritance, a base class serves as a blueprint or template for its derived classes, and each derived class inherits the properties and behaviors (data members and member functions) of the base class. However, each derived class can have its additional unique properties and behaviors, making them distinct from one another.

The main advantage of hierarchical inheritance is code reusability. By defining common attributes and behaviors in a single base class, you can avoid redundant code and make the code easier to manage and maintain.

Here's a simple example to illustrate hierarchical inheritance:

#include<iostream>
#include<string.h>
using namespace std;

// Base Class
class Student
{
protected:
    int roll;
    char name[25];
public:
    void getData()
    {
        cout << "Enter roll number :" << endl;
        cin >> roll;
        cout << "Enter the name :" << endl;
        cin >> name;
    }

    void display()
    {
        cout << "Roll No: " << roll << endl;
        cout << "Name: " << name << endl;
    }
};

// Derived Class with Hierarchical Inheritance
class Result : protected Student
{
protected:
    int subjects[6];
    int obtained_marks = 0;

public:
    void readdata()
    {
        getData();

        cout << "Enter the marks of Hindi: " << endl;
        cin >> subjects[0];
        cout << "Enter the marks of English: " << endl;
        cin >> subjects[1];
    }
    
    void calculateMarks()
    {
        for (int i = 0; i < 6; i++)
        {
            obtained_marks += subjects[i];
        }
    }

    void putdata()
    {
        cout << endl << "Record of a Student is :" << endl;
        display();
        cout << "The marks In Hindi: " << subjects[0] << endl;
        cout << "The marks In English: " << subjects[1] << endl;
        // Derived classes (ScienceResult and CommerceResult) will provide implementation for the remaining subjects.
    }

    void result()
    {
        calculateMarks();
        cout << endl << "Output is :" << endl;
        putdata();
        cout << "Result is: " << obtained_marks << endl;
    }
};

// Derived Class for Science
class ScienceResult : public Result
{
public:
    void readdata()
    {
        Result::readdata();

        cout << "Enter the marks of Physics: " << endl;
        cin >> subjects[2];
        cout << "Enter the marks of Chemistry: " << endl;
        cin >> subjects[3];
        cout << "Enter the marks of Maths: " << endl;
        cin >> subjects[4];
        cout << "Enter the marks of Games: " << endl;
        cin >> subjects[5];
    }

    void putdata()
    {
        Result::putdata();
        cout << "The marks In Physics: " << subjects[2] << endl;
        cout << "The marks In Chemistry: " << subjects[3] << endl;
        cout << "The marks In Maths: " << subjects[4] << endl;
        cout << "The marks In Games: " << subjects[5] << endl;
    }
};

// Derived Class for Commerce
class CommerceResult : public Result
{
public:
    void readdata()
    {
        Result::readdata();

        cout << "Enter the marks of Economics: " << endl;
        cin >> subjects[2];
        cout << "Enter the marks of Business Studies: " << endl;
        cin >> subjects[3];
        cout << "Enter the marks of Accounts: " << endl;
        cin >> subjects[4];
        cout << "Enter the marks of Games: " << endl;
        cin >> subjects[5];
    }

    void putdata()
    {
        Result::putdata();
        cout << "The marks In Economics: " << subjects[2] << endl;
        cout << "The marks In Business Studies: " << subjects[3] << endl;
        cout << "The marks In Accounts: " << subjects[4] << endl;
        cout << "The marks In Games: " << subjects[5] << endl;
    }
};

int main()
{
    int option;
    cout << "Enter 1 for Science:" << endl;
    cout << "Enter 2 for Commerce:" << endl;
    cin >> option;

    if (option == 1)
    {
        ScienceResult obj;
        obj.readdata();
        obj.result();
    }
    else if (option == 2)
    {
        CommerceResult obj;
        obj.readdata();
        obj.result();
    }
    else
    {
        cout << "Wrong Input";
    }

    return 0;
}
Output: with selecting Option 1
Enter 1 for Science:
Enter 2 for Commerce:
1
Enter roll number :
101
Enter the name :
Ram
Enter the marks of Hindi:
99
Enter the marks of English:
96
Enter the marks of Physics:
78
Enter the marks of Chemistry:
87
Enter the marks of Maths:
85
Enter the marks of Games:
88

Output is :

Record of a Student is :
Roll No: 101
Name: Ram
The marks In Hindi: 99
The marks In English: 96
Result is: 533
Output : with selecting Option 2
Enter 1 for Science:
Enter 2 for Commerce:
2
Enter roll number :
1001
Enter the name :
Rekha
Enter the marks of Hindi:
98
Enter the marks of English:
89
Enter the marks of Economics:
86
Enter the marks of Business Studies:
95
Enter the marks of Accounts:
87
Enter the marks of Games:
97

Output is :

Record of a Student is :
Roll No: 1001
Name: Rekha
The marks In Hindi: 98
The marks In English: 89
Result is: 552


Hybrid Inheritance


In C++, hybrid inheritance is a combination of multiple inheritance and hierarchical inheritance. Multiple inheritance allows a class to inherit from multiple base classes, and hierarchical inheritance involves a single base class with multiple derived classes branching out from it. Hybrid inheritance combines these two inheritance types, allowing a class to inherit from multiple base classes, including a hierarchical inheritance structure.

Here's an example to illustrate hybrid inheritance:

#include <iostream>

// Base class A
class A {
public:
    void displayA() {
        std::cout << "This is class A." << std::endl;
    }
};

// Base class B
class B {
public:
    void displayB() {
        std::cout << "This is class B." << std::endl;
    }
};

// Derived class C inherits from A and B (Multiple Inheritance)
class C : public A, public B {
public:
    void displayC() {
        std::cout << "This is class C." << std::endl;
    }
};

// Derived class D inherits from C (Hierarchical Inheritance)
class D : public C {
public:
    void displayD() {
        std::cout << "This is class D." << std::endl;
    }
};

int main() {
    D objD;
    objD.displayA(); // Accessing method from class A
    objD.displayB(); // Accessing method from class B
    objD.displayC(); // Accessing method from class C
    objD.displayD(); // Accessing method from class D

    return 0;
}

Output:
This is class A.
This is class B.
This is class C.
This is class D.

In this example, we have four classes: A, B, C, and D. Class C inherits from classes A and B, demonstrating multiple inheritance. Then, class D inherits from class C, showcasing hierarchical inheritance. This combination of inheritance types is known as hybrid inheritance. With hybrid inheritance, a class can access members from multiple base classes, making it a powerful but potentially complex feature. Care should be taken to design the class hierarchy carefully to avoid issues like the diamond problem, where ambiguity arises due to multiple inheritance paths to a single base class.

#include <iostream>
#include <string.h>
using namespace std;

// Base Class
class Student {
protected:
    int roll;
    char name[25];

public:
    void getData() {
        cout << "Enter roll number :" << endl;
        cin >> roll;
        cout << "Enter the name :" << endl;
        cin >> name;
    }

    void display() {
        cout << "Roll No: " << roll << endl;
        cout << "Name: " << name << endl;
    }
};

// Base Class
class Game {
    char game[45];

public:
    void getGame() {
        cout << "Which Game Do you Like :" << endl;
        cin >> game;
    }

    void showGame() {
        cout << "Game is: " << game << endl;
    }
};

// Derived Class
class Science : protected Student // Single Inheritance
{
protected:
    int subjects[6];

public:
    void readdata(); // declaration
    void putdata();  // declaration
};

void Science::readdata() // definition
{
    getData();

    cout << "Enter the marks of Hindi: " << endl;
    cin >> subjects[0];
    cout << "Enter the marks of English: " << endl;
    cin >> subjects[1];
    cout << "Enter the marks of Physics: " << endl;
    cin >> subjects[2];
    cout << "Enter the marks of Chemistry: " << endl;
    cin >> subjects[3];
    cout << "Enter the marks of Maths: " << endl;
    cin >> subjects[4];
    cout << "Enter the marks of Games: " << endl;
    cin >> subjects[5];
}

void Science::putdata() // definition
{
    cout << endl << "Record of a Student is :" << endl;
    display();
    cout << "The marks In Hindi: " << subjects[0] << endl;
    cout << "The marks In English: " << subjects[1] << endl;
    cout << "The marks In Physics: " << subjects[2] << endl;
    cout << "The marks In Chemistry: " << subjects[3] << endl;
    cout << "The marks In Maths: " << subjects[4] << endl;
    cout << "The marks In Games: " << subjects[5] << endl;
}

// Derived Class
class Commerce : protected Student // Single Inheritance
{
protected:
    int subjects[6];

public:
    void readdata(); // declaration
    void putdata();  // declaration
};

void Commerce::readdata() // definition
{
    getData();

    cout << "Enter the marks of Hindi: " << endl;
    cin >> subjects[0];
    cout << "Enter the marks of English: " << endl;
    cin >> subjects[1];
    cout << "Enter the marks of Economics: " << endl;
    cin >> subjects[2];
    cout << "Enter the marks of Business Studies: " << endl;
    cin >> subjects[3];
    cout << "Enter the marks of Accounts: " << endl;
    cin >> subjects[4];
    cout << "Enter the marks of Games: " << endl;
    cin >> subjects[5];
}

void Commerce::putdata() // definition
{
    cout << endl << "Record of a Student is :" << endl;
    display();
    cout << "The marks In Hindi: " << subjects[0] << endl;
    cout << "The marks In English: " << subjects[1] << endl;
    cout << "The marks In Economics: " << subjects[2] << endl;
    cout << "The marks In Business Studies: " << subjects[3] << endl;
    cout << "The marks In Accounts: " << subjects[4] << endl;
    cout << "The marks In Games: " << subjects[5] << endl;
}

class ScienceResult : private Science, private Game // Hybrid Inheritance
{
    int obtained_marks = 0; // must assign with a value 0. otherwise will give garbage.

public:
    void InsertRecord() {
        Science::readdata();
        Game::getGame();
    }

    void result() {
        for (int i = 0; i < 6; i++) {
            obtained_marks += subjects[i];
        }
        cout << endl << "Output is :" << endl;
        Science::putdata();
        cout << "Result is : " << obtained_marks << endl;
        Game::showGame();
    }
};

class CommerceResult : private Commerce, private Game // Hybrid Inheritance
{
    int obtained_marks = 0;

public:
    void InsertRecord() {
        Commerce::readdata();
        Game::getGame();
    }

    void result() {
        for (int i = 0; i < 6; i++) {
            obtained_marks += subjects[i];
        }
        cout << endl << "Output is :" << endl;
        Commerce::putdata();
        cout << "Result is : " << obtained_marks << endl;
        Game::showGame();
    }
};

int main() {
    int option;
    cout << "Enter 1 for Science:" << endl;
    cout << "Enter 2 for Commerce:" << endl;
    cin >> option;

    if (option == 1) {
        ScienceResult obj;
        obj.InsertRecord();
        obj.result();
    } else if (option == 2) {
        CommerceResult obj;
        obj.InsertRecord();
        obj.result();
    } else {
        cout << "Wrong Input";
    }

    return 0;
}

Enter 1 for Science:
Enter 2 for Commerce:
1
Enter roll number :
101
Enter the name :
Ram
Enter the marks of Hindi:
99
Enter the marks of English:
98
Enter the marks of Physics:
97
Enter the marks of Chemistry:
96
Enter the marks of Maths:
89
Enter the marks of Games:
79
Which Game Do you Like :
Cricket

Output is :

Record of a Student is :

Roll No: 101
Name: Ram

The marks In Hindi: 99
The marks In English: 98
The marks In Physics: 97
The marks In Chemistry: 96
The marks In Maths: 89
The marks In Games: 79
Result is : 558

Game is: Cricket


C++ Aggregation (HAS-A Relationship)

In C++, aggregation is a process in which one class defines another class as any entity reference. It is another way to reuse the class. It is a form of association that represents HAS-A relationship.

In C++, aggregation is usually implemented using pointers or references to objects of the associated class. Aggregation allows classes to work together without one being a fundamental part of the other, promoting flexibility and reusability.



C++ Aggregation Example

Let's see an example of aggregation where Employee class has the reference of Address class as data member. In such way, it can reuse the members of Address class.
#include <iostream>
using namespace std;

class Address {
public:
    string addressLine, city, state, country, pincode;

    Address(string addressLine, string city, string state, string country, string pincode)
        : addressLine(addressLine), city(city), state(state), country(country), pincode(pincode) {}
};

class Employee {
private:
    Address* address; // Employee HAS-A Address

public:
    int id;
    string name;

    Employee(int id, string name, Address* address)
        : id(id), name(name), address(address) {}

    void display() {
        cout << id << " " << name << " " << endl
             << address->addressLine << endl
             << address->city << " " << address->state << endl
             << address->country << " " << address->pincode << endl;
    }
};

int main(void) {
    Address a1 = Address("M30, Sec-14", "Gurgaon", "HR", "India", "122001");
    Employee e1 = Employee(101, "Ram", &a1);
    e1.display();
    return 0;
}

       
Output:
101 Ram
M30, Sec-14
Gurgaon HR
India 122001