You are on page 1of 6

Inheritance

Programming Language 2 (C++)

Inheritance
Inheritance provides an opportunity to reuse the code functionality
and fast implementation time.
When creating a class, instead of writing completely new data
members and member functions, the programmer can designate that
the new class should inherit the members of an existing class.
The mechanism of deriving a new class from an old class/previous
written class in known as inheritance. Also known as is a/kind
of /is a kind of relationship.
The class which is inherited is called base class/parent class/super
class. The class that inherits the base class is known as sub class/child
class/derived class.
class derived-class: access-specifier base-class
2

Inheritance
#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);
cout << "Total area: " << Rect.getArea();
return 0;
}
OUTPUT
Total area: 35
3

Access Control in Inheritance


A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member
functions of derived classes should be declared private in the base class.
We can summarize different access types according to who can access
them in the following way
Access

public

protected

private

Same class

yes

yes

yes

Derived classes yes

yes

no

Outside classes yes

no

no

Multiple Inheritance
Deriving directly from more than one class is usually called
multiple inheritance.
A class may inherit from more than one class by simply specifying more
base classes, separated by commas, in the list of a class's base classes
(i.e., after the colon).
For example, if the program had a specific class to print on screen called
Output, and we wanted our classes Rectangle and Triangle to also
inherit its members in addition to those of Polygon we could write:

class Rectangle: public Polygon, public Output;


class Triangle: public Polygon, public Output;

Multiple Inheritance
#include <iostream>
using namespace std;
class Shape // Base class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
class PaintCost // Base class
PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};

class Rectangle: public Shape, public PaintCost


{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
cout << "Total area: " << Rect.getArea() << endl;
cout << "Total paint cost: $" << Rect.getCost(area);
return 0;
}
OUTPUT
Total area: 35
Total paint cost: $2450
6

You might also like