Single Inheritance

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.





Where 'A' is the base class, and 'B' is the derived class.

 

When one class inherits another class, it is known as single level inheritance.

 

Example

#include <iostream>

using namespace std;

// Base class: Student

class Student {

private:

    int id;

    char name[20];

public:

void setstudent()

{

  cout<<"\n Enter student Id:";

  cin>>id;

  cout<<"\n Enter student Name:";

  cin>>name;

}

void getstudent()

{

  cout<<"\n *******Student Details with Subject marks(Total & Average)******** \n";

  cout<<"Id="<<id<<endl;

  cout<<"Name="<<name<<endl;

}

};


// Derived class: Result

class Result : public Student {

private:

float english_marks,science_marks,computer_marks,total,average;

public:

void setresult()

{

  cout<<"\n Enter English Marks:";

  cin>>english_marks;

  cout<<"\n Enter Science Marks:";

  cin>>science_marks;

  cout<<"\n Enter Computer Marks:";

  cin>>computer_marks;

  total = english_marks + science_marks+ computer_marks;

  average = total / 3.0;

}

void getresult()

{

  cout << "Total Marks: " << total << endl;

  cout << "Average Marks: " << average << endl;

}

};

int main() {

    // Create an object of Result class (which also contains student info)

   Result res;

    // Display student informations

    res.setstudent();

    res.setresult();

    res.getstudent();

    res.getresult();

    return 0;


}


Output:

 Enter student Id:81901

 Enter student Name: Prasanjeet

 Enter English Marks:85

 Enter Science Marks:90

 Enter Computer Marks:88


 *******Student Details with Subject marks(Total & Average)********

Id=81901

Name=Prasanjeet

Total Marks: 263

Average Marks: 87.6667


Process returned 0 (0x0)   execution time : 49.222 s

Press any key to continue

No comments:

Post a Comment