Thursday, 21 September 2017

Multilevel inheritance in C++

/*
 Title: Example to demonstrate multilevel inheritance in C++
*/

#include "iostream"
using namespace std;

class Student{
 protected :
  int rollno;
  string name;
 public:
  void setStudentData(int rno, string sname){ 
   rollno = rno; name=sname;
  }
  void getStudentData(){
   cout<<"\nRollNo: "<<rollno<<"\tName: "<<name;
  }
};

class SubjectMarks: public Student{
 protected:
  int submarks1, submarks2;
 public:
  void setSubMarks(int sub1, int sub2){
   submarks1 = sub1;
   submarks2 = sub2;
  }
  void getSubMarks(){
   cout<<"\nSub1 MArks: "<<submarks1<<"\tSub2 Marks: "<<submarks2;

  }
};

class Result : public SubjectMarks{
 int total;
 public:
  void printResult(){
   total = submarks1 + submarks2;
   cout<<"\nTotal MArks: "<<total<<endl;
  }
};

int main(){
 SubjectMarks sob; 
 sob.setStudentData(101,"Pavan");
 sob.getStudentData();
 
 Result rob;
 rob.setSubMarks(58,42);
 rob.getSubMarks();
 rob.printResult();

 return 0;
}
/*
 OUTPUT
[pavan@localhost Unit-2-Inheritance]$ g++ MultiLevel.cpp
[pavan@localhost Unit-2-Inheritance]$ ./a.out 

RollNo: 101 Name: Pavan
Sub1 MArks: 58 Sub2 Marks: 42
Total MArks: 100
[pavan@localhost Unit-2-Inheritance]$ 

*/

No comments: