0% found this document useful (0 votes)
2 views

Inheritance (1)

Uploaded by

Harkirat Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Inheritance (1)

Uploaded by

Harkirat Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Inheritance

What Is Inheritance?
• Inherit Definition -
Derive quality and characteristics from parents or
ancestors. Like you inherit features of your
parents.
• Example:
"She had inherited the beauty of her mother"
• Inheritance in Object Oriented Programming can
be described as a process of creating new classes
from existing classes.
• New classes inherit some of the properties
and behaviour 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(“child class”).
• Inheritance is a technique of code reuse. It
also provides possibility to extend existing
classes by creating derived classes.
The "is a" Relationship
• Inheritance establishes an "is a" relationship
between classes.
– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
Types of Inheritance
• Single Inheritance: It is the inheritance hierarchy
wherein one derived class inherits from one base class.
• Multiple Inheritance: It is the inheritance hierarchy
wherein one derived class inherits from multiple base
class(es).
• Hierarchical Inheritance: It is the inheritance hierarchy
wherein multiple subclasses inherit from one base
class.
• Multilevel Inheritance: It is the inheritance hierarchy
wherein subclass acts as a base class for other classes.
• Hybrid Inheritance: The inheritance hierarchy that
reflects any legal combination of other four types of
inheritance.
Access specifier

Access public protected private

Same class ✔ ✔ ✔

Derived ✔ ✔ ❌
classes

Outside ✔ ❌ ❌
classes
Protected Members and
Class Access
• protected member access specification:
like private, but accessible by objects of
derived class
Inheritance – Terminology and
Notation in C++
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Base // base class
{
. . .
};
class Derived : modeofinheritance Base
{ // derived class
. . .
};
modeofinheritance can be public, private and
protected.
Mode of Inheritace
• Mode of Inheritance: determines how private,
protected, and public members of base class
are inherited by the derived class
Mode of Inheritance
How inherited base class
members
Base class members appear in derived class
private: x private x is inaccessible
protected: y base class
private: y
public: z private: z

private: x protected x is inaccessible


protected: y base class protected: y
public: z protected: z

private: x public x is inaccessible


protected: y base class protected: y
public: z public: z
Mode of Inheritance
class Grade class Test : public Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
public class access, it public members:
Test(int, int);
looks like this: void setScore(float);
float getScore();
char getLetter();
Mode of Inheritance
class Grade class Test : protected Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
protected class access, it public members:
Test(int, int);
looks like this: protected members:
void setScore(float);
float getScore();
float getLetter();
Mode of Inheritance
class Grade class Test : private Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
private class access, it void setScore(float);
float getScore();
looks like this: float getLetter();
public members:
Test(int, int);
Modes of Inheritance

• 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.
• 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.
• 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.
Single Inheritance
In single inheritance, a class is allowed to
inherit from only one class. i.e. one derived
class inherits one base class only.
Single Inheritance
#include <iostream>
using namespace std; int main()
class base { {
int i, j;
derived ob;
public:
void set(int a, int b) ob.setk(20); // access member of
derived class
{ i=a; j=b; }
void show() ob.set(1, 2); // access member of
base
{ cout << i << " " << j << "\n"; }
}; ob.show(); // access member of
base
class derived : public base {
int k; ob.showk(); // access member of
derived class
public:
void setk(int x) { k=x; } return 0;
void showk() { cout << k << "\n"; } }
};
// This program won't public:
compile. void setk(int x) { k=x; }
#include <iostream> void showk()
using namespace std; { cout << k << "\n"; }
class base { };
int i, j; int main()
public: {
void set(int a, int b) { i=a; j=b; derived ob;
} ob.set(1, 2);
void show() { cout << i << " " // error, can't access set()
<< j << "\n";}
}; ob.show();
// Public elements of base are // error, can't access show()
private in derived. return 0;
class derived : private base { }
int k;
Multiple Inheritance
Multiple Inheritance is a feature of C++ where a
class can inherit from more than one classes. i.e
one derived is inherited from more than one base
classes.
Inheriting Multiple Base Classes
#include <iostream> // Inherit multiple base classes.
using namespace std; class derived: public base1, public
class base1 { base2 {
protected: public:
int x; void set(int i, int j) { x=i; y=j; }
public: };
void showx() { cout << x << "\n"; } int main()
}; {
class base2 { derived ob;
protected: ob.set(10, 20);
int y; // provided by derived
public: ob.showx(); // from base1
void showy() {cout << y << "\n";} ob.showy(); // from base2
}; return 0;
}
Multi-level Inheritance
#include <iostream> //derived2 class
using namespace std; class derived2 : public derived
//Base class { public:
class base { void display3(){
public: cout << "\n2nd Derived class
void display1() { content.";
cout << "\nBase class content."; } } };
}; int main()
//derived class {
class derived : public base derived2 D;
{ D.display3();
public: D.display2();
void display2() D.display1();
{ return(0);
cout << "1st derived class content."; }
} };
Hierarchical Inheritance
#include <iostream> void disp() {
#include <string.h> cout << "Age: " << age <<
using namespace std; endl; cout << "Gender: "
//Base Class << gender << endl; }
class member { };
char gender[10]; //derived from member
int age; class stud : public member
public: { char level[20];
void get() public:
{ cout << "Age: "; cin >> age; void getdata() {
member::get();
cout << "Gender: "; cin >> cout << "Class: ";
gender; }
cin >> level; }
Continue...
void disp2() void disp3() {
{ member::disp(); member::disp();
cout << "Level: " << level; cout << "Salary: Rs." <<
} }; salary << endl;
//staff class derived from } };
member
class staff : public member int main() {
{ float salary; //member M;
public: staff S;
void getdata() { stud s;
member::get(); s.getdata();
cout << "Salary: Rs."; s.disp();
cin >> salary; } S.getdata();
S.disp();
return(0); }
Constructors and Destructors in Base
and Derived Classes
• Derived classes can have their own
constructors and destructors.
• When an object of a derived class is created,
the base class’s constructor is executed first,
followed by the derived class’s constructor.
• When an object of a derived class is
destroyed, its destructor is called first, then
that of the base class.
//EXAMPLE ~derived()
#include<iostream> { cout << "Destructing derived\n"; }
Using namespace std; };
//base class int main()
class base { {
public: derived ob;
base() // do nothing but construct and
{ cout << "Constructing base\n"; } destruct ob
~base() return 0;
{ cout << "Destructing base\n"; } }
};
//derived class
class derived: public base {
public: Program Output
derived() Constructing base
{ Constructing derived
cout << "Constructing derived\n"; } Destructing derived
Destructing base
Constructors and Destructors with
Multiple Base Classes
• Constructors are called in order of derivation,
left to right, as specified in derived's
inheritance list.
• Destructors are called in reverse order, right to
left.
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
using namespace std; public:
class base1 { derived() { cout << "Constructing
public: derived\n"; }
base1() { cout << "Constructing ~derived() { cout << "Destructing
base1\n"; } derived\n"; }
~base1() { cout << "Destructing };
base1\n"; } int main()
}; {
class base2 { derived ob;
public: // construct and destruct ob
base2() { cout << "Constructing return 0;
base2\n"; } } Program Output:
~base2() { cout << "Destructing Constructing base1
base2\n"; } Constructing base2
}; Constructing derived
Destructing derived
Destructing base2
Destructing base1
Passing Arguments to
Base Class Constructor
derived-constructor(arg-list) : base1(arg-list),
base2(arg-list),
// ...
baseN(arg-list)
{
// body of derived constructor
}

UTA009 Inheritance, Virtual Base Class &


3/19/2021 28
Abstract Class
Order of Constructor Call
• Base class constructors are always called in
the derived class constructors. Whenever you
create derived class object, first the base class
default constructor is executed and then the
derived class's constructor finishes execution.

UTA009 Inheritance, Virtual Base Class &


3/19/2021 29
Abstract Class
//EXAMPLE // derived uses x; y is passed
#include <iostream> along to base.
using namespace std; derived(int x, int y): base(y)
class base { { j=x;
protected: cout << "Constructing
int i; derived\n"; }
public: ~derived() { cout << "Destructing
derived\n"; }
base(int x) void show() { cout << i << " " << j
{ i=x; cout << "Constructing << "\n"; }
base\n"; } };
~base() { cout << "Destructing int main()
base\n"; }
}; {
class derived: public base { derived ob(3, 4);
int j; ob.show(); // displays 4 3
public: return 0;
}

UTA009 Inheritance, Virtual Base Class &


3/19/2021 30
Abstract Class
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
using namespace std; int j;
class base1 { public:
protected: int i; derived(int x, int y, int z): base1(y),
public: base2(z)
base1(int x) { i=x; cout << { j=x; cout << "Constructing
"Constructing base1\n"; } derived\n"; }
~base1() { cout << "Destructing ~derived() { cout << "Destructing
base1\n"; }}; derived\n"; }
class base2 { void show() { cout << i << " " << j <<
" " << k << "\n"; }
protected: int k;
};
public:
int main()
base2(int x) { k=x; cout <<
"Constructing base2\n"; } { derived ob(3, 4, 5);
~base2() { cout << "Destructing ob.show(); // displays 4 3 5
base1\n"; } }; return 0; }
UTA009 Inheritance, Virtual Base Class &
3/19/2021 31
Abstract Class
Here’s what actually happens when base is
instantiated:

• Memory for base is set aside


• The appropriate Base constructor is called
• The initialization list initializes variables
• The body of the constructor executes
• Control is returned to the caller

UTA009 Inheritance, Virtual Base Class &


3/19/2021 32
Abstract Class
Here’s what actually happens when derived is
instantiated:

• Memory for derived is set aside (enough for both


the Base and Derived portions)
• The appropriate Derived constructor is called
• The Base object is constructed first using the
appropriate Base constructor. If no base
constructor is specified, the default constructor
will be used.
• The initialization list initializes variables
• The body of the constructor executes
• Control is returned to the caller

UTA009 Inheritance, Virtual Base Class &


3/19/2021 33
Abstract Class
Note
• It is important to understand that arguments
to a base-class constructor are passed via
arguments to the derived class' constructor.
Therefore, even if a derived class‘ constructor
does not use any arguments, it will still need
to declare one if the base class requires it. In
this situation, the arguments passed to the
derived class are simply passed along to the
base.
UTA009 Inheritance, Virtual Base Class &
3/19/2021 34
Abstract Class
Why is Base class Constructor called
inside Derived class ?
• Constructors have a special job of initializing
the object properly. A Derived class
constructor has access only to its own class
members, but a Derived class object also have
inherited property of Base class, and only base
class constructor can properly initialize base
class members. Hence all the constructors are
called, else object wouldn't be constructed
properly.
UTA009 Inheritance, Virtual Base Class &
3/19/2021 35
Abstract Class
// This program contains an int main() {
error and will not compile. derived3 ob;
#include <iostream> ob.i = 10; // this is
ambiguous, which i???
using namespace std;
ob.j = 20;
class base {
ob.k = 30;
public: int i; }; // i ambiguous here, too
class derived1 : public base { ob.sum = ob.i + ob.j + ob.k;
public: int j; }; // also ambiguous, which i?
class derived2 : public base { cout << ob.i << " ";
public: int k; }; cout << ob.j << " " << ob.k ;
class derived3 : public cout << ob.sum;
derived1, public derived2 { return 0;
public: int sum; }; }

UTA009 Inheritance, Virtual Base Class &


3/19/2021 36
Abstract Class
Discussion
• which i is being referred to, the one in derived1
or the one in derived2?
• Because there are two copies of base present in
object ob, there are two ob.is! As you can see,
the statement is inherently ambiguous.
• There are two ways to remedy the preceding
program.
• The first is to apply the scope resolution operator
to i and manually select one i. Example (on next
slide).
UTA009 Inheritance, Virtual Base Class &
3/19/2021 37
Abstract Class
// This program uses explicit int main()
scope resolution to select i. {
#include <iostream> derived3 ob;
using namespace std; ob.derived1::i = 10; // scope
class base { public: int i; }; resolved, use derived1's i
// derived1 inherits base. ob.j = 20;
class derived1 : public base { ob.k = 30;
public: int j; }; // scope resolved
// derived2 inherits base. ob.sum = ob.derived1::i + ob.j +
class derived2 : public base { ob.k;
public: int k; }; // also resolved here
class derived3 : public cout << ob.derived1::i << " ";
derived1, public derived2 { cout << ob.j << " " << ob.k << " ";
public: int sum; }; cout << ob.sum;
return 0; }
UTA009 Inheritance, Virtual Base Class &
3/19/2021 38
Abstract Class
Discussion
• As you can see, because the :: was applied,
the program has manually selected derived1's
version of base.
• What if only one copy of base is actually
required? Is there some way to prevent two
copies from being included in derived3? This
solution is achieved using virtual base classes.

UTA009 Inheritance, Virtual Base Class &


3/19/2021 39
Abstract Class
• When two or more objects are derived from a
common base class, you can prevent multiple
copies of the base class from being present in
an object derived from those objects by
declaring the base class as virtual when it is
inherited.
• You accomplish this by preceding the base
class' name with the keyword virtual when it is
inherited.
• For example, here is another version of the
example program in which derived3 contains
only one copy of base: Example Program Next
Slide

UTA009 Inheritance, Virtual Base Class &


3/19/2021 40
Abstract Class
// This program uses virtual base int main()
classes.
#include <iostream> {
using namespace std; derived3 ob;
class base { public: int i; };
ob.i = 10; // now unambiguous
// derived1 inherits base as virtual. ob.j = 20;
ob.k = 30;
class derived1 : virtual public base { // unambiguous
public: int j; };
ob.sum = ob.i + ob.j + ob.k;
// derived2 inherits base as virtual. // unambiguous
cout << ob.i << " ";
class derived2 : virtual public base {
public: int k; }; cout << ob.j << " " << ob.k << " ";
cout << ob.sum;
class derived3 : public derived1, return 0;
public derived2
{ public: int sum; }; }

UTA009 Inheritance, Virtual Base Class &


3/19/2021 41
Abstract Class
Discussion
• As you can see, the keyword virtual precedes the
rest of the inherited class‘specification.
• Now that both derived1 and derived2 have
inherited base as virtual, any multiple inheritance
involving them will cause only one copy of base
to be present.
• Therefore, in derived3, there is only one copy of
base and ob.i = 10 is perfectly valid and
unambiguous.
UTA009 Inheritance, Virtual Base Class &
3/19/2021 42
Abstract Class
Pros and cons of inheritance
1. Reuse the methods and data of a class
2. Extend the existing class by adding new
data and functions
3. Modify the existing class by overloading its
methods
4. Adds extra memory overload for the
compiler as it has to keep records of the
parent as well as the child class
Friend function and Inheritance
• Friendship is not inherited
• What is the output of the following
program?
class A {
protected: int i;
public: A(int a) { i = a;}
friend void show();
};
class B: public A {
int j;
public: B(int a, int b) : A(a) {j=b;}
};
void show() {
B b(-2,55);
cout<<b.i<<", "<<b.j; }

int main() {show();}


Output

[Error] 'int B::j' is private

So parent’s friend is not child’s friend,


what about vice versa?
Thanks

You might also like