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

Module-3-C++

Module 3 notes

Uploaded by

bnsagar2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module-3-C++

Module 3 notes

Uploaded by

bnsagar2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Constructors, Destructors, Inheritance

Module-3
Constructors, Destructors & Inheritance

Introduction
We have seen, so far, a few examples of classes being implemented. In all the
cases, we have used member functions such as putdata() and setvalue() to
provide initial values to the private member variables. For example, the following
statement
A.input();
invokes the member function input(), which assigns the initial values to the data
items of object A. Similarly, the statement
x.getdata(100,299.95);
passes the initial values as arguments to the function getdata(), where these
values are assigned to the private variables of object x. All these ‘function call’
statements are used with the appropriate objects that have already been
created. These functions cannot be used to initialize the member variables at the
time of creation of their objects.
Providing the initial values as described above does not conform with the
philosophy of C++ language. We stated earlier that one of the aims of C++ is to
create user-defined data types such as class, that behave very similar to the
built-in types. This means that we should be able to initialize a class type variable
(object) when it is declared, much the same way as initialization of an ordinary
variable. For example,
int m = 20;
float x = 5.75;
are valid initialization statements for basic data types.
Similarly, when a variable of built-in type goes out of scope, the compiler
automatically destroys the variable. But it has not happened with the objects we
have so far studied. It is therefore clear that some more features of classes need
to be explored that would enable us to initialize the objects when they are created

Dept. of CSE,RYMEC,Ballari Page 1


Constructors, Destructors, Inheritance

and destroy them when their presence is no longer necessary.


C++ provides a special member function called the constructor which
enables an object to initialize itself when it is created. This is known as automatic
initialization of objects. It also provides another member function called the
destructor that destroys the objects when they are no longer required.

3.1 Constructors
 A constructor is a ‘special’ member function whose task is to initialize the
objects of its class.
 It is special because its name is the same as the class name.
 The constructor is invoked whenever an object of its associated class is
created.
 It is called constructor because it constructs the values of data members of
the class.
A constructor is declared and defined as follows:
// class with a constructor
class integer
{
int m, n;
public:
integer(void); // constructor declared
.....
.....
};
integer :: integer(void) // constructor defined
{
m = 0; n = 0;
}

Dept. of CSE,RYMEC,Ballari Page 2


Constructors, Destructors, Inheritance

 When a class contains a constructor like the one defined above, it is


guaranteed that an object created by the class will be initialized
automatically.
For example, the declaration

integer int1; // object int1 created

not only creates the object int1 of type integer but also initializes its data members
m and n to zero.
 There is no need to write any statement to invoke the constructor function
(as we do with the normal member functions).
 If a ‘normal’ member function is defined for zero initialization, we would need
to invoke this function for each of the objects separately. This would be very
inconvenient, if there are a large number of objects.

Example Program:
#include<iostream.h>
#include<conio.h>
class Example
{
// Variable Declaration
int a, b;
public:
//Constructor
Example()
{
// Assign Values In Constructor
a = 10;
b = 20;
cout << "I am Constructor\n";
}
void Display()
{
cout << "Values :" << a << "\t" << b;
}
};
void main()
{
Example Object;

Dept. of CSE,RYMEC,Ballari Page 3


Constructors, Destructors, Inheritance

// Constructor invoked.
Object.Display();
getch();
}

Output:

I am Constructor
Values :10 20

The constructor functions have some special characteristics. These are the
following:

 They should be declared in the public section.


 They are invoked automatically when the objects are created.
 They do not have return types, not even void and therefore, and they cannot
return values.
 They cannot be inherited, though a derived class can call the base class
constructor.
 Like other C++ functions, they can have default arguments.
 Constructors cannot be virtual. (Meaning of virtual will be discussed later in
Chapter 9.)
 We cannot refer to their addresses.
 An object with a constructor (or destructor) cannot be used as a member of a
union.
 They make ‘implicit calls’ to the operators new and delete when memory
allocation is required.

Remember, when a constructor is declared for a class, initialization of the class


objects becomes mandatory.

Dept. of CSE,RYMEC,Ballari Page 4


Constructors, Destructors, Inheritance

3.2 Destructors


A destructor, as the name implies, is used to destroy the objects that
have been created by a constructor.
 Like a constructor, the destructor is a member function whose name is the
same as the class name but is preceded by a tilde.
For example, the destructor for the class integer can be defined as shown below:

~integer()
{
}
 A destructor never takes any argument nor does it return any value.
 It will be invoked implicitly by the compiler upon exit from the program (or
block or function as the case may be) to clean up storage that is no longer
accessible.
 It is a good practice to declare destructors in a program since it releases
memory space for future use.
 Whenever new is used to allocate memory in the constructors, we should
use delete to free that memory.

Example Program:
#include <iostream.h>
#include<conio.h>
int cCount = 0;
int dCount = 0;
class Test
{
public:
// User-Defined Constructor
Test()
{
// Number of times constructor is called
cCount++;
cout << "No. of Object created: " << cCount
<< endl;
}

Dept. of CSE,RYMEC,Ballari Page 5


Constructors, Destructors, Inheritance

// User-Defined Destructor
~Test()
{
dCount++;
cout << "No. of Object destroyed: " << dCount
<< endl;
// Number of times destructor is called
}
};
// driver code
int main()
{
Test t, t1, t2, t3;
return 0;
}

Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 1
No. of Object destroyed: 2
No. of Object destroyed: 3
No. of Object destroyed: 4

Dept. of CSE,RYMEC,Ballari Page 6


Constructors, Destructors, Inheritance

Inheritance

3.3 Introduction
 Reusability is yet another important feature of OOP. It is always nice if we could
reuse something that already exists rather than trying to create the same all over
again.
 It would not only save time and money but also reduce frustration and increase
reliability.
 For instance, the reuse of a class that has already been tested, debugged and used
many times can save us the effort of developing and testing the same again.
 Fortunately, C++ strongly supports the concept of reusability.
 The C++ classes can be reused in several ways. Once a class has been written and
tested, it can be adapted by other programmers to suit their requirements. This is
basically done by creating new classes, reusing the properties of the existing ones.
 The mechanism of deriving a new class from an old one is called inheritance (or
derivation).
 The old class is referred to as the base class and the new one is called the derived
class or subclass.
 The derived class inherits some or all of the traits from the base class.
 A class can also inherit properties from more than one class or from more than one
level.
 A derived class with only one base class, is called single inheritance and one with
several base classes is called multiple inheritance.
 On the other hand, multiple derived (child) classes inherit from a single base
(parent) class. This process is known as hierarchical inheritance.
 The mechanism of deriving a class from another ‘derived class’ is known as multilevel
inheritance.

Figure shows various forms of inheritance that could be used for writing extensible
programs. The direction of arrow indicates the direction of inheritance. (Some authors
show the arrow in opposite direction meaning “inherited from”.)

Dept. of CSE,RYMEC,Ballari Page 7


Constructors, Destructors, Inheritance

Fig 3.1 Forms of Inheritance

Dept. of CSE,RYMEC,Ballari Page 8


Constructors, Destructors, Inheritance

3.4 Defining Derived Classes


 A derived class can be defined by specifying its relationship with the base class in
addition to its own details.
The general form of defining a derived class is;

class derived-class-name : visibility-mode base-class-name


{
..... //
..... // members of derived class
..... //
};

 The colon indicates that the derived-class-name is derived from the base-class-
name.
 The visibility-mode is optional and, if present, may be either private or public.
 The default visibility-mode is private. Visibility mode specifies whether the features
of the base class are privately derived or publicly derived.

Examples:

class derived: private base // private derivation


{
members of derived
};
class derived: public base // public derivation
{
members of derived
};
class derived: base // private derivation by default
{
members of derived
};

Dept. of CSE,RYMEC,Ballari Page 9


Constructors, Destructors, Inheritance

3.5 Single Inheritance

Fig 3.2 Single Inheritance

Let us consider a simple example to illustrate inheritance. Below program


rogram shows a
base class B and a derived class D. The class B contains one private data member, one
private data member, and three public member functions. The class D contains one private
privat
data member and two public member functions.

Program: Single Inheritance: Public

#include<iostream.h>
#include<conio.h>
class B
{
int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void set_ab();
int get_a(void);
void show_a(void);
};
class D : public B // public derivation
{
int c;
public:
void mul(void);
void display(void);
};
//------------------------------------------------------
------------------------------------------------------
void B :: set_ab(void)
{
a = 5; b = 10;
}

Dept. of CSE,RYMEC,Ballari Page 10


Constructors, Destructors, Inheritance

int B :: get_a()
{
return a;
}
void B :: show_a()
{
cout << “a = ” << a << “\n”;
}
void D :: mul()
{
c = b * get_a();
}
void D :: display()
{
cout << “a = ” << get_a() << “\n”;
cout << “b = ” << b << “\n”;
cout << “c = ” << c << “\n\n”;
}
//------------------------------------------------------
int main()
{
D d;
d.set_ab();
d.mul();
d.show_a();
d.display();
d.b = 20;
d.mul();
d.display();
return 0;
}

Output:
Output:
a=5
a=5
b = 10
c = 50
a=5
b = 20
c = 100

Dept. of CSE,RYMEC,Ballari Page 11


Constructors, Destructors, Inheritance

Program: Single Inheritance: Private


#include<iostream.h>
#include<conio.h>
class B
{
int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(void);
};
class D : private B // private derivation
{
int c;
public:
void mul(void);
void display(void);
};
// -------------------------------------------------------
void B :: get_ab(void)
{
cout << “Enter values for a and b: ”;
cin >> a >> b;
}
int B :: get_a()
{
return a;
}
void B :: show_a()
{
cout << “a = ” << a << “\n”;
}
void D :: mul()
{
get_ab();
c = b * get_a(); // ‘a’ cannot be used directly
}

Dept. of CSE,RYMEC,Ballari Page 12


Constructors, Destructors, Inheritance

void D :: display()
{
show_a(); // outputs value of ‘a’
cout << “b = ” << b << “\n”
<< “c = ” << c << “\n\n”;
}
// -------------------------------------------------------
int main()
{
D d;
// d.get_ab(); WON’T WORK
d.mul();
// d.show_a(); WON’T WORK
d.display();
// d.b = 20; WON’T WORK; b has become private
d.mul();
d.display();
return 0;
}

Output :
Enter values for a and b: 5 10
a=5
b = 10
c = 50

Enter values for a and b: 12 20


a = 12
b = 20
c = 240

Dept. of CSE,RYMEC,Ballari Page 13


Constructors, Destructors, Inheritance

3.6 Multiple Inheritance


 A class can inherit the attributes of two or more classes as shown in Fig. 3.3. This is
known as multiple inheritance
inheritance.
 Multiple inheritance allows us to combine the features of several existing classes as
a starting point for defining new classes.
 It is like a child inheriting the physical features of one parent and the intelligence of
another.

Fig 3.3 Multiple Inheritance

where, visibility may be either public or private.. The base classes are separated by
commas.

Example:
class P : public M, public N
{
public:
void display(void);
};

Dept. of CSE,RYMEC,Ballari Page 14


Constructors, Destructors, Inheritance

Classes M and N have been specified as follows:


class M
{
protected:
int m;
public:
void get_m(int);
};
void M :: get_m(int x)
{
m = x;
}
class N
{
protected:
int n;
public:
void get_n(int);
};
void N :: get_n(int y)
{
n = y;
}

Program: Multiple Inheritance

#include<iostream.h>
#include<conio.h>
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;
public:

Dept. of CSE,RYMEC,Ballari Page 15


Constructors, Destructors, Inheritance

void get_n(int);
};
class P : public M, public N
{
public:
void display(void);
};
void M :: get_m(int x)
{
m = x;
}
void N :: get_n(int y)
{
n = y;
}
void P :: display(void)
{
cout << “m = ” << m << “\n”;
cout << “n = ” << n << “\n”;
cout << “m*n = ” << m*n << “\n”;
}
int main()
{
P p;
p.get_m(10);
p.get_n(20);
p.display();
return 0;
}

Output:

m = 10
n = 20
m*n = 200

Dept. of CSE,RYMEC,Ballari Page 16


Constructors, Destructors, Inheritance

3.7 Hierarchical Inheritance


 Another interesting application of inheritance is to use it as a support to the
hierarchical design of a program.
 Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below that level.
 As an example, Fig. 3.4 shows a hierarchical classification of students in a university.
 Another example could be the cclassification
lassification of accounts in a commercial
comme bank as
shown in Fig. 3.5.
 All the students have certain things in common and, similarly, all the accounts
possess certain common features.

Fig 3.4
4 Hierarchical classification of students

Fig 3.5 Classification of bank accounts

Dept. of CSE,RYMEC,Ballari Page 17


Constructors, Destructors, Inheritance

 In C++, such problems can be easily converted into class hierarchies.


 The base class will include all the features that are common to the subclasses.
 A subclass can be constructed by inheriting the properties of the base class.
 A subclass can serve as a base class for the lower level classes, and so on.

3.8 Hybrid Inheritance


 There could be situations where we need to apply two or more types of inheritance
to design a program.
 Assume that we have to give weightage for sports before finalising the results.
 The weightage for sports is stored in a separate class called sports.
 The new inheritance relationship between the various classe
classess would be as shown in
Fig. 3.6.

Fig 3.
3.6 Multilevel, multiple inheritance

The sports class might look like


class sports
{
protected:
float score;
public:
void get_score(float);
void put_score(void);
};

Dept. of CSE,RYMEC,Ballari Page 18


Constructors, Destructors, Inheritance

The result will have both the multilevel and multiple inheritances and its declaration would
be as follows:
class result : public test, public sports
{
.....
.....
};

Where test itself is a derived class from student. That is,


class test : public student
{
.....
.....
};

Below Program illustrates the implementation of both multilevel and multiple inheritance

Program: Hybrid Inheritance

#include<iostream.h>
#include<conio.h>
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number = a;
}
void put_number(void)
{
cout << “Roll No: ” << roll_number << “\n”;
}
};
class test : public student
{
protected:
float part1, part2;
public:
void get_marks(float x, float y)
{
part1 = x; part2 = y;
}

Dept. of CSE,RYMEC,Ballari Page 19


Constructors, Destructors, Inheritance

void put_marks(void)
{
cout << “Marks obtained: ” << “\n”
<< “Part1 = ” << part1 << “\n”
<< “Part2 = ” << part2 << “\n”;
}
};
class sports
{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}
void put_score(void)
{
cout << “Sports wt: ” << score << “\n\n”;
}
};
class result : public test, public sports
{
float total;
public:
void display(void);
};
void result :: display(void)
{
total = part1 + part2 + score;
put_number();
put_marks(); Output:
put_score();
Roll No:1234
cout << “Total Score: ” << total << “\n”;
}
Marks Obtained:
int main()
{ Part1=27.5
result student_1;
student_1.get_number(1234); Part2=33
student_1.get_marks(27.5, 33.0);
student_1.get_score(6.0); Sports wt: 6
student_1.display();
return 0; Total Score:66.5
}

Dept. of CSE,RYMEC,Ballari Page 20

You might also like