Inheritance Unit3
Inheritance Unit3
Inheritance Unit3
Unit 3
Inheritance
// Base class
class Parent
{
public:
int id_p;
};
return 0;
}
class A {
public: int x;
protected: int y;
private: int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
class Person {
int id;
char name[100];
public:
void set_p()
{
cout << "Enter the Id:";
cin >> id;
cout << "Enter the Name:";
cin >> name;
}
void display_p()
{
cout << endl <<"Id: "<< id << "\nName: " << name <<endl;
}
class Student : private Person {
char course[50];
int fee;
public:
void set_s()
{
set_p();
cout << "Enter the Course Name:";
cin >> course;
cout << "Enter the Course Fee:";
cin >> fee;
}
void display_s()
{
display_p();
cout <<"Course: "<< course << "\nFee: " << fee << endl;
}
};
int main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}
Output
#include<iostream>
#include<string.h>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p(int,char[]);
void display_p();
};
void Person::display_p()
{
cout<<endl<<id<<"\t"<<name;
}
class Student: private Person
{
char course[50];
int fee;
public:
void set_s(int,char[],char[],int);
void display_s();
};
void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}
main()
{
Student s;
s.set_s(1001,"Ram","B.Tech",2000);
s.display_s();
return 0;
}
C++ program to explain single inheritance
#include<iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes
Car obj;
return 0;
}
C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Output
• This is a Vehicle
• Objects with 4 wheels are vehicles
• Car has 4 Wheels
C++ program to explain multiple inheritance
#include <iostream>
using namespace std;
int main()
{
// Creating object of sub class will invoke the
//constructor of base classes.
Car obj;
return 0;
}
Output
• This is a Vehicle
• This is a 4 wheeler Vehicle
C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;