Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Object Oriented Programming-

Inheritance
Inheritance
• Inheritance is one of the key features of Object-oriented programming in C++. It
allows us to create a new class (derived class) from an existing class (base class).
• The derived class inherits the features from the base class and can have additional
features of its own. For example,
class Animal {
// eat() function
// sleep() function
};
class Dog : public Animal {
// bark() function
};

2
is-a relationship
• Inheritance is an is-a relationship. We use inheritance only
if an is-a relationship is present between the two classes.
• Here are some examples:
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.

3
Advantages
• Saves memory space
• Saves time
• Increases reliability of the code
• Saves the developing and testing efforts

4
Syntax
class drivedClass_name : access_mode baseClass_name
e.g.
Class Rectangle : Public Shape

5
Inheritance Example
// base class // derived class
class Animal { class Dog : public Animal {

public: public:
void eat() { void bark() {
cout << "I can eat!" << endl; cout << "I can bark!!!" << endl;
} }
};
void sleep() { int main() {
cout << "I can sleep!" << endl; // Create object of the Dog class
} Dog dog1;
};
// Calling members of the base class
Output dog1.eat();
I can eat! dog1.sleep();
I can sleep!
I can bark!!! // Calling member of the derived class
dog1.bark();
return 0;} 6
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)

7
Example Cont..
class CPolygon { class CTriangle: public CPolygon {
protected: public:
int width, height; int area ()
public: { return (width * height / 2);}
void set_values (int a, int b)
};
{ width=a; height=b;}
}; int main () {
class CRectangle: public CPolygon { CRectangle rect;
public: CTriangle trgl;
int area ()
rect.set_values (4,5);
{ return (width * height); }
}; trgl.set_values (4,5);
cout << rect.area() << endl;
Output cout << trgl.area() << endl;
20 return 0;}
10
8
C++ Protected Members
• The access modifier protected is especially relevant when it comes
to C++ inheritance.

• Like private members, protected members are inaccessible outside


of the class. However, they can be accessed by derived classes and
friend classes/functions.

• We need protected members if we want to hide the data of a class,


but still want that data to be inherited by its derived classes.

9
Example
// base class
class Animal { // derived class
int main() {
class Dog : public Animal { // Create object of the Dog class
private: Dog dog1;
string color; public:
void setType(string tp) {
protected: type = tp; // Calling members of the base class
string type; } dog1.eat();
dog1.sleep();
public: void displayInfo(string c) {
void eat() { cout << "I am a " << type << endl;
dog1.setColor("black");
cout << "I can eat!" << endl; cout << "My color is " << c << endl;
} } // Calling member of the derived class
void sleep() {
dog1.bark();
void bark() {
cout << "I can sleep!" << endl; cout << "I can bark!!!" << endl; dog1.setType("mammal");
} }
}; // Using getColor() of dog1 as argument
void setColor(string clr) {
color = clr; // getColor() returns string data
}
Output dog1.displayInfo(dog1.getColor());
I can eat!
string getColor() { I can sleep! return 0;
return color;
I can bark!!! }
}
}; I am a mammal
My color is black 10
Access Control and 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.

Access Public Protected Private


Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

11
Access Modes in C++ Inheritance
• So far, we have used the public keyword to inherit a class from a
previously-existing base class. However, we can also use the private
and protected keywords to inherit classes. For example,

class Animal {
// code class Cat : protected Animal {
}; // code
}
class Dog : private Animal {
// code
};

12
Access Modes in C++ Inheritance
• The various ways we can derive classes are known as
access modes. These access modes have the following
effect:
• Modes of Inheritance
1. Public mode: If we derive a sub class from a Public base class.
Then the public member of the base class will become public in
the derived class and protected members of the base class will
become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base
class. Then both public member and protected members of the
base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class.
Then both public member and protected members of the base
class will become Private in derived class. 13
Modes of Inheritance

14
Modes of Inheritance Example
class A
class C : protected A
{
{
public: // x is protected
int x; // y is protected
protected: // z is not accessible from C
int y; };
private: class D : private A // 'private' is default
int z; for classes
}; {
// x is private
// y is private
class B : public A
// z is not accessible from D
{ };
// x is public
// y is protected
// z is not accessible from B
};
15
Order of Constructor and Destructor Execution
• Base class constructors are always executed first
• Destructors are executed in exactly the reverse order of
constructors

16
Order of Constructor and Destructor
Execution Cont..
class Base{
public:
Base ( )
{cout << "Inside Base constructor" << endl; }
~Base ( ) { cout << "Inside Base destructor" << endl;}
};
Output
class Derived : public Base{
public:
Inside Base constructor
Derived ( ){cout<< "Inside Derived constructor\n";}
Inside Derived constructor
~Derived ( ){cout<<"Inside Derived destructor\n";}
Inside Derived destructor
};
void main( )
Inside Base destructor
{
Derived x;

}
17
Order of Constructor and Destructor Execution
Cont..

18
Order of Constructor and Destructor Execution
Cont..

19
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 explicitly.
○ You can pass the arguments given to the derived class constructor to the
constructor for the base class

20
Inheriting Constructors Cont..
class Person{ class Student: public Person{
protected: public:
void setAge(int a)
int age; { age = a; }
public: };
Person()
{age = -5;} int main(){
Person(int a) Student p; Default constructor
cout<<p.getAge();
{age = a;} Student p1(15);
int getAge() }
{return age;} Parameterized constructor can’t be inherited
}; Compilation Error

21
Inheriting Constructors Cont..
class Student: public Person{
public:
Student(int age):Person(age){
}
void setAge(int a){ age = a; }

}; In the implementation of the constructor for the


derived class, the parameter passed to the
derived class constructor is passed down to the
base class constructor.

22
Inheriting Constructors Cont..

derived class constructor base class constructor

Square(int side) : Rectangle(side,side)

derived constructor base constructor


parameter parameters

23
Inheriting Constructors Cont..
class base{ class derv1 : public base{
private: private:
int x; int y;
public: public:
base (int x1){ derv1 (int yy, int xx) : base (xx){
cout<<"Base's constructor cout << " Derv1's constructor executed";
executed"; y = yy;
x = x1; cout<<y<<endl;
cout<<x<<endl; }
} };
};
void main ( ){ Base’s constructor executed 30
derv1 d (20, 30);} Derv1’s constructor executed 20

24
Inheriting Constructors Cont..
//base class // sub class
class Parent { class Child : public Parent {
int x; int j;
public:
public: // sub class's parameterized constructor
// base class's parameterized constructor Child(int x) : Parent(x) {
Parent(int i) { cout << "Inside sub class's parameterized
x = i; constructor"<< endl; }
cout << "Inside base class's parameterized };
constructor"<< endl;
}
}; // main function
int main()
Output {
Inside base class's
parameterized constructor // creating object of class Child
Child obj1(10);
Inside sub class's parameterized
return 0;
constructor }
25
Function Overriding
• When a derived class has a function with the same name as a
function of the base class, it is called Function Overriding. Both
functions must have the same parameters in both classes.

26
Function Overriding Example

class BaseClass { // sub class class DerivedClass: public BaseClass{


public: public:
void print(){ void print() {
cout<<"Parent Class Function"; cout<<"Child Class Function";
} }
}; };

// main function
int main() {
DerivedClass obj;
Output obj.print();
Child Class Function return 0;
}
27
Access Overridden Function
To access the overridden function of the base class, we
use the scope resolution operator ::

28
Access Overridden Function Example
class BaseClass { // sub class class DerivedClass: public BaseClass{
public: public:
void disp(){ void disp() {
cout<<"Parent Class Function"; cout<<"Child Class Function";
} }
}; };

// main function
int main() {
Output DerivedClass obj1, obj2;
Child Class Function obj1.disp();
Parent Class Function // access print() function of the Base class
obj2.BaseClass::disp();
return 0;
}

29
Access Overridden Function inside the
Derived Class

30
Access Overridden Function inside the
Derived Class Example
class BaseClass { // sub class class DerivedClass: public BaseClass{
public: public:
void disp(){ void disp() {
cout<<"Parent Class Function"; cout<<"Child Class Function";
} BaseClass::print();
}; }
};

// main function
Output int main() {
Child Class Function DerivedClass obj1;
Parent Class Function obj1.disp();
return 0;
}

31
Overriding Functions Example
class Circle : public Point
class Point { {
protected: double radius;
int x,y; public:
public:
Point(int a,int b) Circle(int a,int b,double
{ c):Point(a,b)
cout<<"\nPoint Class Constructor"; {
x=a; cout<<"\nCircle Class Constructor";
y=b; } radius = c;}
~Point()
{ ~Circle()
cout<<"\nPoint Class Destructor";}
{cout<<"\nCircle Class Destructor"; }
void display()
{ void display()
cout<<"Point = ["<<x<<","<<y<<"]“;} {
}; Point::display();
cout<<" and Radius = "<<radius;}
};
32
Overriding Functions Example Cont..
class Cylinder: public Circle
{ int main(){
double height; Cylinder object(3,4,2.5,6);
public: object.display();
Cylinder(int a,int b,double r,double h) return 0;
:Circle(a,b,r) }
{
height=h;
cout<<"\nCylinder Class Constructor\n";} Output
Point Class Constructor
~Cylinder() Circle Class Constructor
Cylinder Class Constructor
{ cout<<"\nCylinder Class Destructor"; }
Point = [3,4] , Radius = 2.5 & Height = 6
void display() Cylinder Class Destructor
{ Circle Class Destructor
Circle::display(); Point Class Destructor
cout<<" & Height = "<<height;}
}; 33
Function Overloading Vs Function
Overriding
Function Overload Function Override

The scope is the same The scope is different

Signatures must differ (ex: parameter) Signatures must be same

Number of overloading functions possible Only one overriding function possible

May occur without inheritance It mainly occurs due to inheritance

34

You might also like