#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
Showing posts with label inheritance. Show all posts
Showing posts with label inheritance. Show all posts
Thursday, 28 April 2016
Another example for inheritance
Single Inheritance
#include<iostream.h>
#include<conio.h>
class employee
{
protected:
int emp_id;
char emp_name[20];
public:
void accept()
{
cout<<"Enter name and emp id=";
cin>>emp_name>>emp_id;
}
void display()
{
cout<<"Name="<<emp_name<<endl;
cout<<"ID="<<emp_id<<endl;
}
};
class worker:public employee
{
protected:
int salary;
public:
void accept1()
{
cout<<"Enter Salary=";
cin>>salary;
}
void display1()
{
cout<<"Salary:"<<salary<<endl;
}
};
void main()
{
clrscr();
worker w;
w.accept();
w.accept1();
w.display();
w.display1();
getch();
}
/*Output:
Enter name and emp id=qqq 123
Enter Salary=200
Name=qqq
ID=123
Salary:200
*/
#include<conio.h>
class employee
{
protected:
int emp_id;
char emp_name[20];
public:
void accept()
{
cout<<"Enter name and emp id=";
cin>>emp_name>>emp_id;
}
void display()
{
cout<<"Name="<<emp_name<<endl;
cout<<"ID="<<emp_id<<endl;
}
};
class worker:public employee
{
protected:
int salary;
public:
void accept1()
{
cout<<"Enter Salary=";
cin>>salary;
}
void display1()
{
cout<<"Salary:"<<salary<<endl;
}
};
void main()
{
clrscr();
worker w;
w.accept();
w.accept1();
w.display();
w.display1();
getch();
}
/*Output:
Enter name and emp id=qqq 123
Enter Salary=200
Name=qqq
ID=123
Salary:200
*/
What is Inheritance?
Inheritance is a mechanism of deriving a new class form the existing old class.
The old class is referred as base class and new class is referred as the derived class.
New classes inherit some of the properties and behavior of the existing classes. An existing class that is "parent" of a new class is called a base class. New class that inherits properties of the base class is called a derived class.
So basically Inheritance is a technique of code reuse.
Please comment for any program related to Inheritance.
The old class is referred as base class and new class is referred as the derived class.
New classes inherit some of the properties and behavior of the existing classes. An existing class that is "parent" of a new class is called a base class. New class that inherits properties of the base class is called a derived class.
So basically Inheritance is a technique of code reuse.
Please comment for any program related to Inheritance.
Subscribe to:
Posts (Atom)