PRACTICAL – 12.1
Write a program to implement single inheritance. Show the consequences of deriving a class in public, protected and private manner with a simple example.
#include <iostream>using namespace std;class Parent{int pvt;protected:int prot;public:int pub;void setdata(int a, int b){pvt = a;prot = b;}};class child : public Parent{public:void print(){cout << "Private : Private data can not be inheritaded " << endl;cout << "Protected : " << prot << endl;cout << "Public : " << pub << endl;}};int main(){child kit;kit.setdata(11, 12);kit.pub = 10;kit.print();return 0;}
PRACTICAL – 12.2
Consider a simple example. Class student stores the roll-number, class test stores the marks in two subjects and class result contains the total marks obtained in the test. The class result inherits the details of the marks obtained and roll number of students through multilevel inheritance. Write a program to demonstrate the above
#include <iostream>using namespace std;class student{protected:int rollnumer;public:void setrollnumber(int a){rollnumer = a;}};class Test : public student{protected:int mark1, mark2;public:void setdmarks(int a, int b){mark1 = a;mark2 = b;}};class Result : public Test{public:void print(){cout << "Roll Number" << rollnumer << endl;cout << "Maths " << mark1 << "obtain from 100." << endl;cout << "Science " << mark2 << "obtain from 100." << endl;cout << "Result is " << float(mark1 + mark2) / 2 << endl;}};int main(){Result s[10];s[0].setrollnumber(1);s[0].setdmarks(90, 89);s[0].print();return 0;}
PRACTICAL – 12.3
Extend the program in (2) to add a sports class. The result class inherits the details of marks obtained from class test and the performance in sports from the sports class (hybrid inheritance).
#include <iostream>#include <string>using namespace std;class student{protected:int rollnumber;};class Test : public student{protected:int mark1, mark2;public:void setdmarks(int a, int b){mark1 = a;mark2 = b;}virtual void setrollnumber(int a){rollnumber = a;}virtual int getdata(){return rollnumber;}};class Sport : public student{protected:int sport_score;string grade;public:void setscore(){cout << "Howmany task are completer from 5 : ";cin >> sport_score;if (sport_score == 5){grade = "A+";}else if (sport_score == 4){grade = "B+";}else if (sport_score == 3){grade = "C+";}else if (sport_score == 2){grade = "D+";}else{grade = "E";}}};class Result : public Test, public Sport{public:void print(){cout << "Roll Number" << this->getdata() << endl;cout << "Maths " << mark1 << "obtain from 100." << endl;cout << "Science " << mark2 << "obtain from 100." << endl;cout << "Result is " << float(mark1 + mark2) / 2 << endl;cout << "Sports Score grade is " << grade << endl;}};int main(){Result s[10];s[0].setrollnumber(1);s[0].setdmarks(90, 89);s[0].setscore();s[0].print();return 0;}
0 Comments