Example:2
When we have same name for base class and derived class member functions .
Sol:
#include<iostream> using namespace std; class student { private: int roll; char name[20]; public: void read(); void show(); }; class physical:public student { private: float age,ht,wt; public: void read(); void show(); }; void student::read() { cout<<"Enter roll and name "; cin>>roll>>name; } void student::show() { cout<<"roll "<<roll<<" name "<<name<<endl; } void physical::read() { student::read(); cout<<"Enter age,ht and weight "; cin>>age>>ht>>wt; } void physical::show() { student::show(); cout<<"age "<<age<<" height "<<ht<<" weight " <<wt<<endl; } int main() { physical p; cout<<"size of student "<<sizeof(student)<<endl; cout<<"size of office "<<sizeof(physical)<<endl; p.read(); p.show(); return(0); }
Output:
size of student 24
size of office 36
Enter roll and name 101
Sumit
Enter age,ht and weight 15
4
35
roll 101 name Sumit
age 12 height 4 weight 35
Example:3
Write a C++ program to declare a class named employee with attributes as employee number and name. Declare another class named office with attributes as department number, department name and basic salary. The class office is the derived class of employee. Take input for the details and display them.
Base class: Employee(empno,name)
Derived class:Office(dno,dname,bsal)
Sol:
//single inheritance #include<iostream> using namespace std; class employee { private: int empno; char name[20]; public: void read(); void show(); }; class office:public employee { private: int dno; char dname[20]; float bsal; public: void read(); void show(); }; void employee::read() { cout<<"Enter empno and name "; cin>>empno>>name; } void employee::show() { cout<<"Empno "<<empno<<" name "<<name<<endl; } void office::read() { employee::read(); cout<<"Enter dno , dname and basic salary "; cin>>dno>>dname>>bsal; } void office::show() { employee::show(); cout<<"dno "<<dno<<" dname "<<dname<<" bsal "<<bsal<<endl; } int main() { office o; cout<<"size of class employee "<<sizeof(employee)<<endl; cout<<"size of class office "<<sizeof(office)<<endl; o.read(); o.show(); return(0); }
Output:
size of class employee 24
size of class office 52
Enter empno and name 1001
Ashmit
Enter dno , dname and basic salary 10
Sales
45000
Empno 1001 name Ashmit
dno 10 dname Sales bsal 45000