Easy way to understand oops is to code it, run it, debug it. Repeat it till you get something new every iteration.
The below program is self explanatory and easy to understand.
Leave comment if you find hard to understand and I will be there to help (Let me know what error you get)
Follow step by step, first code for Person class and create person object and see is it working fine and then for Student class. At the end inherit Person as public to Student.
#include <bits/stdc++.h>
using namespace std;
class Person{
int id;
char name[20];
public:
void setP(){
cout<<"Enter Id: "; cin>>id;
cout<<"Enter name: "; cin>>name;
}
void displayP(){
cout<<"Id: "<<id<<"\tName:"<<name<<endl;
}
};
class Student: public Person{
char course[20];
int fee;
public:
void setS(){
cout<<"Enter course: "; cin>>course;
cout<<"Enter fee: "; cin>>fee;
}
void displayS(){
cout<<"Course is: "<<course<<"\tfee: "<<fee<<endl;
}
};
int main(){
//Inherit person class behaviour in student class
Student s;
s.setP();
s.setS();
s.displayP();
s.displayS();
return 0;
}
Now inhert Person class privately to Student class
Before looking to code try once
class Student: private Person{
char course[20];
int fee;
public:
void setS(){
setP();
cout<<"Enter course: "; cin>>course;
cout<<"Enter fee: "; cin>>fee;
}
void displayS(){
displayP();
cout<<"Course is: "<<course<<"\tfee: "<<fee<<endl;
}
};
int main(){
Student s;
s.setS();
s.displayS();
return 0;
}
Crux: Publicly inherited class are accessible to child class object and it's member function. But when class is privately inherited it can be accessed only through child class member functions.
Top comments (0)