Beruflich Dokumente
Kultur Dokumente
Using C++
Third Edition
Understanding Inheritance
Introduction
Inheritance allows to use Re-usability concept.
Once a class is written; it can be used and tested
by other programmers.
Mechanism of deriving new class from old-one is
called Inheritance.
Old class Base class
New class Derived class
Types of Inheritance
A class can Inherit properties in following ways:
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multi-level Inheritance
Hybrid Inheritance
10
11
12
13
14
Private Inheritance
17
Public derivation
Class base
{
private:
int base_a;
protected:
int base_b;
public:
void base_set();
};
Class derived: public base
{
private:
int derived_a;
protected:
int derived_b;
public:
void derived_set();
};
Protected derivation
Class base
{
private:
int base_a;
protected:
int base_b;
public:
void base_set();
};
Class derived: protected base
{
private:
int derived_a;
protected:
int derived_b;
public:
void derived_set();
};
Private derivation
Class base
{
private:
int base_a;
protected:
int base_b;
public:
void base_set();
};
Class derived: private base
{
private:
int derived_a;
protected:
int derived_b;
public:
void derived_set();
};
constructors
destructors
friend functions
overloaded new operators
overloaded = operators
21
22
Ambiguity Resolution
24
25
26
Receiving 3
parameters
27
Initializes inherited
base class members
28
29
Same outputData()
function is used
30
31
32
33
34
Example
Derived class object created as:
36
37
38
39
40
41
Constructor
42
constructor
43
constructor
44
45
46
Hybrid Inheritance
Aggregation
Here object of one class is declared as member of another class
Object of
Date class
class student
class Date
{
{
private:
private:
int id_no;
int month, day, year;
Date dob;
public:
public:
Date(int m, int d, int year)
student(int id, int d, int m, int y)
{
: dob(d,m,y)
Constructor is
month = m;
{
called
day = d;
id_no = id;
year= y;
}
}
}
};
Object Slicing
Base & Derived class
class base
{
public:
int i, j;
};
class derived: public base
{
public:
int k;
};
Main() function
int main()
{
base b;
derived d;
b=d;
}
Derived class
members are
copies one-by-one
into base class
51
copied
Object Delegation
It is behaviour of object in terms of another object.
Alternative to class inheritance.
Here, 2 objects are involved in handling request:
A receiving object delegates operations to its
delegate.
53
Example
A class object
declared
Constructor
Function of class A
called to perform
task
Object of class A
passed in constructor