Inheritance in C++
Inheritance
"Student is a type of a person " is inheritance by nature. To implement this relationship code snippet is as under;
#include<iostream.h>
class Person{
private:
char* name;
int Age;
public:
Person(){
name="";
Age=0;
}
Person( char* n,int A){
name=n;
Age=A;
}
char* getName(){return name;}
int getAge(){
return Age;
}
void Eat(){//non static
cout<<"Person is eating";
}
static void Walk(){//static
cout<<"Person is walking";
}
};
class Student: public Person{
private:
int RollNo;
float CGPA;
public:
Student(){
Person::Person();
RollNo=0;
CGPA=0.0;
}
Student( char* n,int A,int r, float c){
Person::Person(n,A);
RollNo=r;
CGPA=c;
}
int getRollNo(){
return RollNo;
}
float getCGPA(){
return CGPA;
}
};
main(){
Person p("Ali",14);
Student s("Ali",14,01,2.5);
cout<<p.getName()<<endl;
cout<<p.getAge()<<endl;
cout<<s.getRollNo()<<endl;
cout<<s.getCGPA()<<endl;
p.Eat();//non static
cout<<endl;
Person::Walk();//static
system("pause");
}
***********************************************
By Hafiz Muhammad Umar Hayat
Comments
Post a Comment