Professional Documents
Culture Documents
Introduction
• Inheritance is one of the key feature of object-oriented
programming including C++ which allows user to create a
new class(derived class) from a existing class(base class)
• The derived (child) class inherits all feature from a base
(parent) class and it can have additional features of its
own
CSSE-2133 Object Oriented Programming 3
Introduction Cont..
CSSE-2133 Object Oriented Programming 4
Advantages
• Saves memory space
• Saves time
• Increases reliability of the code
• Saves the developing and testing efforts
CSSE-2133 Object Oriented Programming 5
Syntax
class drivedClass_name :
access_mode baseClass_name
e.g.
Rectangle : Public Shape
CSSE-2133 Object Oriented Programming 6
Private Inheritance
• In private mode, the protected and public members of
super class become private members of derived class
• Syntax is
class Subclass : private Superclass OR
class Subclass : Superclass // Default
CSSE-2133 Object Oriented Programming 8
Protected Inheritance
• In protected mode, the public and
protected members of Super class
becomes protected members of Sub
class
• Syntax is
class Subclass : protected
Superclass
CSSE-2133 Object Oriented Programming 9
Example
class Shape {
protected:
float length;
float width;
};
Class Rectangle : public Shape{
public:
float getArea ();
} ;
CSSE-2133 Object Oriented Programming 11
Example Cont..
•Implement a Polygon class that contains length and width
data members. Derive two classes Triangle and Rectangle
class from Polygon class and calculate area (Area of
rectangle is length x width and area of triangle is (length x
width)/2)
CSSE-2133 Object Oriented Programming 12
Example Cont..
class CPolygon { class CTriangle: public
protected: CPolygon {
int width, height; public:
public: int area (){ return (width *
void set_values (int a, int height / 2); }
b) };
{ width=a; height=b;} void main () {
}; CRectangle rect;
class CRectangle: public
CTriangle trgl;
CPolygon {
public: rect.set_values (4,5);
int area () trgl.set_values (4,5);
{ return (width * height); } cout << rect.area() << endl;
}; cout << trgl.area() << endl;
}
CSSE-2133 Object Oriented Programming 13
Inheriting Constructors
• If the base class constructor takes no parameters then the
inheritance is implicit - you don’t need to do anything!
• If the base class constructor takes parameters then each
derived class needs to declare a constructor with the
same parameters
• You can pass the arguments given to the derived class constructor
to the constructor for the base class
CSSE-2133 Object Oriented Programming 18
derived base
constructor constructor
parameter parameters
CSSE-2133 Object Oriented Programming 21
void main()
{
ABC cc1, cc2(10), cc3(10,20);
cc1.display();
cc2.display();
cc3.display();
}