bachelor of computer applications semester-ii object oriented ...

263
1 CU IDOL SELF LEARNING MATERIAL (SLM) BACHELOR OF COMPUTER APPLICATIONS SEMESTER-II OBJECT ORIENTED PROGRAMMING BCA122

Transcript of bachelor of computer applications semester-ii object oriented ...

1

CU IDOL SELF LEARNING MATERIAL (SLM)

BACHELOR OF COMPUTER

APPLICATIONS

SEMESTER-II

OBJECT ORIENTED PROGRAMMING

BCA122

2

CU IDOL SELF LEARNING MATERIAL (SLM)

SLM SPECIALLY PREPARED FOR

CU IDOL STUDENTS

Chairman

CHANDIGARH UNIVERSITY

Institute of Distance and Online Learning

Course Development Committee

Prof. (Dr.) Parag Diwan

Vice Chancellor, Chandigarh University, Gharuan, Punjab Advisors

Prof. (Dr.) Bharat Bhushan, Director – IGNOU

Prof. (Dr.) Majulika Srivastava, Director – CIQA, IGNOU Programme Coordinators & Editing Team

Master of Business Administration (MBA)

Coordinator – Dr. Rupali Arora

Master of Computer Applications (MCA)

Coordinator – Dr. Raju Kumar

Master of Commerce (M.Com.)

Coordinator – Dr. Aman Jindal

Master of Arts (Psychology)

Coordinator – Dr. Samerjeet Kaur

Master of Arts (English) Coordinator

– Dr. Ashita Chadha

Bachelor of Business Administration (BBA)

Coordinator – Dr. Simran Jewandah

Bachelor of Computer Applications (BCA)

Coordinator – Dr. Manisha Malhotra

Bachelor of Commerce (B.Com.) Coordinator

– Dr. Minakshi Garg

Bachelor of Science (Travel &Tourism Management)

Co-ordinator – Dr. Shikha Sharma

Bachelor of Arts (General)

Co-ordinator – Ms. Neeraj Gohlan

Academic and Administrative Management

Prof. (Dr.) R. M. Bhagat Prof. (Dr.) S.S. Sehgal

Executive Director – Sciences Registrar

Prof. (Dr.) Abhishek Prof. (Dr.) Inderpreet Kaur

Executive Director – Management Director – IDOL

Prof. (Dr.) Manaswini Acharya

Executive Director – Liberal Arts

© No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any

form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the authors and thepublisher.

Printed and Published by:

SCHOOLGURU EDUSERVE PVT LTD

B-903, Western Edge II, Western Express Highway, Borivali (E),

Mumbai - 400066

Call Us:

+91 22 4896 8005

Mail Us:

[email protected]

For: CHANDIGARH UNIVERSITY

Institute of Distance and Online Learning

3

CU IDOL SELF LEARNING MATERIAL (SLM)

First Published in 2020

All rights reserved. No Part of this book may be reproduced or transmitted, in any form or

by any means, without permission in writing from Chandigarh University. Any person who

does any unauthorized act in relation to this book may be liable to criminal prosecution and

civil claims for damages. This book is meant for educational and learning purpose. The

authors of the book has/have taken all reasonable care to ensure that the contents of the

book do not violate any existing copyright or other intellectual property rights of any

person in any manner whatsoever. In the even the Authors has/ have been unable to track

any source and if any copyright has been inadvertently infringed, please notify the

publisher in writing for corrective action.

4

CU IDOL SELF LEARNING MATERIAL (SLM)

CONTENT

Unit 1: Fundamentals of C++ 1 ......................................................................................... 4

Unit 2: Fundamentals of C++ 2 ....................................................................................... 20

Unit 3 : Classes and Objects 1 ......................................................................................... 42

Unit 4 : Classes and Objects 2 ......................................................................................... 75

Unit 5:Constructors and Destructors .............................................................................. 98

Unit6:Inheritance ........................................................................................................... 119

Unit 7 :Polymorphism.................................................................................................... 156

Unit8:Exception Handling ............................................................................................. 187

Unit 9:Pointer & Virtual Function ................................................................................ 203

Unit 10: Dynamic memory allocation ........................................................................... 225

Unit 11: Files .................................................................................................................. 238

5

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 1FUNDAMENTALS OF C++ 1

Structure

1.0 LearningObjectives

1.1 Introduction

1.2 Featured of object-oriented programming

1.3 Difference between object oriented and procedure oriented programming

1.4 Difference between structure and classes

1.5 Summary

1.6 KeyWords/Abbreviations

1.7 LearningActivity

1.8 Unit End Questions (MCQ andDescriptive)

1.9 References

1.0LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Explain the basic concepts of object-oriented programming.

Discuss Difference between object oriented and procedure oriented programming.

State Difference between structure and classes.

1.1INTRODUCTION

Featured of object- Object-oriented programming (OOP) is a computer programming model

that organizes software design around data, or objects, rather than functions and logic. An

object can be defined as a data field that has unique attributes and behavior.OOP focuses on

6

CU IDOL SELF LEARNING MATERIAL (SLM)

the objects that developers want to manipulate rather than the logic required to manipulate

them. This approach to programming is well-suited for programs that are large, complex and

actively updated or maintained. Object-Oriented Programming (OOP) is the term used to

describe a programming approach based on objects and classes. The object-oriented

paradigm allows us to organize software as a collection of objects that consist of both data

and behavior. This is in contrast to conventional functional programming practice that only

loosely connects data and behaviour.Since the 1980s the word 'object' has appeared in

relation to programming languages, with almost all languages developed since 1990 having

object-oriented features. Some languages have even had object-oriented features retro-fitted.

It is widely accepted that object-oriented programming is the most important and powerful

way of creating software.

1.2 FEATURED OF OBJECT ORIENTED PROGRAMMING

The prime purpose of C++ programming was to add object orientation to the C

programming language, which is in it one of the most powerful programming languages.

The core of the pure object-oriented programming is to create an object, in code, that has

certain properties and methods. While designing C++ modules, we try to see whole world in

the form of objects. For example a car is an object which has certain properties such as

color, number of doors, and the like. It also has certain methods such as accelerate, brake,

and so on. Procedural programming deals with functional parts of the problem. Programmers

identify what actions must be taken to solve the problem at hand. Let us now, try to

understand what aspect of problems is dealt with in object-oriented approach. We shall be

discussing some essential concepts that make a programming approach object-oriented. In

object-oriented parlance, a problem is viewed in terms of the following concepts:

1. Objects

2. Classes

3. Data abstraction

4. Data encapsulation

7

CU IDOL SELF LEARNING MATERIAL (SLM)

5. Inheritance

6. Polymorphism

7. Dynamic binding

8. Message passing

Object oriented programming-is not the right of any particular language. Although

languages like C and Pascal can be used but programming becomes clumsy and may

generate confusion when program grow in size. A language that is specially designed to

support the OOP concepts makes it easier to implement them. To claim that they are object-

oriented they should support several concepts of OOP. Depending upon the features they

support, they are classified into the following categories:

1. Object-based programming languages

2. Object-oriented programming languages.

Table 1.1 characteristics of object oriented programming

8

CU IDOL SELF LEARNING MATERIAL (SLM)

Major features required by object-based programming are:

1. Data encapsulation.

2. Data hiding and access mechanisms.

3. Automatic initialization and clear-up of objects.

4. Operator overloading.

Languages that support programming with objects are said to be object-based programming

languages. These do not support inheritance and dynamic binding ADA is a typical example

Object oriented programming incorporates all of objects-based programming features along

with two additional features, namely, inheritance and dynamic binding. Thus Object oriented

programming = Object-based features + inheritance + dynamic binding.

1.3 DIFFERENCE BETWEEN OBJECT ORIENTED ANDPROCEDURE

9

CU IDOL SELF LEARNING MATERIAL (SLM)

ORIENTED PROGRAMMING

Computer programming has been around for some decades now. The style and manner in

which people have been developing programs itself has undergone a sea change. In the early

days of computer development programming was looked upon as some kind of black magic

– to be understood only by a few wizards mostly the people who had designed the computer.

However, the entire scenario has changed now. In the modern programming parlance, at

least in most of the commercial and business applications areas, programming has been

made independent of the target machine. This machine independent characteristic of

programming has given rise to a number of different methodologies in which programs can

now be developed. We will particularly concern ourselves with two broad programming

approaches – or paradigm as they are called in the present context.

1. Object-oriented paradigm

2. Procedure-oriented paradigm

Object-oriented Programming Paradigm -The term Object-oriented Programming (OOP)

is widely used, but experts do not seem to agree on its exact definition. However, most

experts agree that OOP involves defining Abstract Data Types (ADT) representing complex

real-world or abstract objects and organizing programs around the collection of ADTs with

an eye toward exploiting their common features. The term data abstraction refers to the

process of defining ADTs; inheritance and polymorphism refer to the mechanisms that

enable you to take advantage of the common characteristics of the ADTs – the objects in

OOP. Before going any further into OOP, take note of two points. First, OOP is only a

method of designing and implementing software. Use of object-oriented techniques does not

impart anything to a finished software product that the user can see. However, as a

programmer while implementing the software, you can gain significant advantages by using

object-oriented methods, especially in large software projects. Because OOP enables you to

remain close to the conceptual, higher-level model of the real world problem you are trying

to solve, you can manage the complexity better than with approaches that force you to map

the problem to fit the features of the language. You can take advantage of the modularity of

objects and implement the

10

CU IDOL SELF LEARNING MATERIAL (SLM)

Benefits of OOPS- Object-orientation contribute to the solution of many problems

associated with the development and quality of software products. The technology provides

greater programmer productivity, better quality of software and lesser maintenance cost. The

principle advantages are:

1. Through inheritance, we can eliminate redundant code and extend the use of existing

classes.

2. We can build programs from the standard working modules that communicate with one

another, rather than having to start writing the code from scratch. This leads to saving of

development time and higher productivity.

3. The principle of data hiding help the programmer to build secure programs that cannot be

invaded by code in other parts of the program.

4. It is possible to have multiple instances of an object to co-exist without any interference.

5. It is possible to map objects in the problem domain to those objects in the program.

6. It is easy partition the work in a project based on objects.

7. The data-centered design approach enables us to capture more details of a model in

implementable form.

8. Object oriented systems can be easily upgraded from small to large systems.

9. Message passing techniques for communication between objects makes the interface

descriptions with external systems much simpler. 10. Software complexity can be easily

managed.

Applications of OOP-

Object-oriented approach offers perhaps the most logical description of the real

world. Therefore, it can be applied in almost all the situations of problem solving.

Because of its effectiveness in problem solving and programming, OOP has been

adopted all over the software industry.

The existing systems are being migrated to OOP. One important aspect of OOP that

11

CU IDOL SELF LEARNING MATERIAL (SLM)

is particularly beneficial is the framework, which encompasses all the phases of a

system development. Thus, OOA (Object Oriented Analysis), OOD (Object Oriented

Design), OOT (Object Oriented Testing) etc. are far more suitable tools than their

non-object-oriented counterparts. Above all, the reusability feature of the Object

Oriented approach has facilitated the rapid growth of software both in variety and

scope.

Procedure-oriented Programming -Paradigm Before you get into OOP, take a look at

conventional procedure-oriented programming in a language such as C. Using the

procedure-oriented approach; you view a problem as a sequence of things to do such as

reading, calculating and printing. Conventional programming using high-level languages is

commonly known as procedure-oriented programming.Example: COBOL, FORTRAN and

C You organize the related data items into C structures and write the necessary functions

(procedures) to manipulate the data and, in the process, complete the sequence of tasks that

solve your problem.

Fig 1.1 Typical Structure of Procedure-oriented Programs

A typical program structure for procedural programming is shown in Figure 1.1. The

technique of hierarchical decomposition has been used to specify the tasks to be completed

in order to solve a problem. Procedure oriented programming basically consists of writing a

12

CU IDOL SELF LEARNING MATERIAL (SLM)

list of instructions for the computer to following and organizing these instructions into

groups known as functions. We normally use a flowchart to organize these actions and

represent the flow of control from one action to another. While we concentrate on the

development of functions, very little attention is given to the data that are being used by

various functions. What happens to the data? How are they affected by the functions that

work on them? In a multi-function program, many important data items are placed as global

so that they may be accessed by all the functions. Each function may have its own local data.

Figure 1.2 shows the relationship of data and functions in a procedure-oriented program.

Global data are more vulnerable to an inadvertent change by a function. In a large program it

is very difficult to identify what data is used by which function. In case we need to revise an

external data structure, we should also revise all functions that access the data. This provides

an opportunity for bugs to creep in.

Fig 1.2 Relationships of Data and Functions in Procedural Programming

The basic feature of Procedural-oriented Programming is to reuse the same code at different

places in the program without coping it. Another serious drawback with the procedural

approach is that it does not model real world problems very well. This is because functions

are action-oriented and do not really corresponding to the elements of the problem. Some

characteristics exhibited by procedure-oriented programming are:

1. Emphasis is on doing things (algorithms).

2. Large programs are divided into smaller programs known as functions.

13

CU IDOL SELF LEARNING MATERIAL (SLM)

3. Most of the functions share global data.

4. Data move openly around the system from function to function.

Table 1.2 Procedural oriented programming VS Object oriented programming

Procedural oriented programming Object oriented programming

In procedural programming, program is

divided into small parts called functions.

In object oriented programming, program

is divided into small parts called objects.

Procedural programming follows top down

approach.

Object oriented programming

follows bottom up approach.

There is no access specifier in procedural

programming.

Object oriented programming have access

specifiers like private, public, protected

etc.

Adding new data and function is not easy. Adding new data and function is easy.

Procedural programming does not have any

proper way for hiding data so it is less

secure.

Object oriented programming provides

data hiding so it is more secure.

In procedural programming, overloading is

not possible.

Overloading is possible in object oriented

programming.

In procedural programming, function is In object oriented programming, data is

14

CU IDOL SELF LEARNING MATERIAL (SLM)

Procedural oriented programming Object oriented programming

more important than data. more important than function.

Procedural programming is based on unreal

world.

Object oriented programming is based

on real world.

Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.

1.4 DIFFERENCE BETWEEN STRUCTURE AND CLASSES

A Structure is not secure and cannot hide its implementation details from the end user while

a class is secure and can hide its programming and designing details. Following are the

points that expound on this difference:

1) Members of a class are private by default and members of a struct are public by default.

2) When deriving a struct from a class/struct, default access-specifier for a base class/struct

is public. And when deriving a class, default access specifier is private.

Table 1.3 structures vs. class

Basis for comparison Structure Class

Basic If access specifier is not

declared, by default all

member are 'public'.

If access specifier is not

declared, by default all

members are 'private'.

15

CU IDOL SELF LEARNING MATERIAL (SLM)

Basis for comparison Structure Class

Declaration struct structure_name {

type struct_element 1;

type struct_element 2;

type struct_element 3;

.

};

class class_name{

data member;

member function;

};

Instance Instance of 'structure' is

called 'structure variable'.

Instance of a 'class' is called

'object'.

Polymorphism and

inheritance

Not supported Supports polymorphism and a

class can also be inherited.

Nature Value type Reference type

Memory is allocated on Stack Heap

Null values Not possible Can have null values

Requires constructor and

destructor

No Yes

1.5 SUMMARY

16

CU IDOL SELF LEARNING MATERIAL (SLM)

Programming practices have evolved considerably over the past few decades.

By the end of last decade, millions and millions lines of codes have been designed

and implemented all over the word.

The main objective is to reuse these lines of codes. More and more software

development projects were software crisis.

It is this immediate crisis that necessitated the development of object-oriented

approach which supports reusability of the existing code.

Software is not manufactured. It is evolved or developed after passing through

various developmental phases including study, analysis, design, implementation, and

maintenance. Conventional programming using high level languages such as

COBOL, FORTRAN and C is commonly known as procedures-oriented

programming.

In order to Solve a problem, a hierarchical decomposition has been used to specify

the tasks to be completed.

OOP is a method of designing and implementing software.

Since OOP enables you to remain close to the conceptual, higher-level model of the

real-world problem, you can manage the complexity better than with approaches that

force you to map the problem to fit the features of the language.

Some essential concepts that make a programming approach object-oriented are

objects, classes, Data abstraction, Data encapsulation, Inheritance, Polymorphism,

dynamic binding and message passing.

The data and the operation of a class can be disclosed public, protected or private.

OOP provides greater programmer productivity, better quality of software and lesser

maintenance cost.

Depending upon the features they support, they are classified as object based

programming languages and object-oriented programming languages.

17

CU IDOL SELF LEARNING MATERIAL (SLM)

Object oriented approach offers the most logical description of the real world. The

framework of OOP encompasses all the phases of system development.

The reusability features of OOP have facilitated the rapid growth of software.

1.5KEY WORDS/ABBREVIATIONS

Classes: A class represents a set of related objects.

Data Abstraction: Abstraction refers to the act of representing essential-features

without including the background details or explanations.

Data Encapsulation: The wrapping up to data and functions into a single unit (class)

is known as encapsulation.

Design: The term design describes both a final software system and a process by

which it is developed.

Object-oriented Programming Paradigm: The term object-oriented programming

(OOP) is widely used, but experts do not seem to agree on its exact definition.

Objects: Objects are the basic run-time entities in an object-oriented system.

Polymorphism: Polymorphism means the ability to take more than one form.

Alphanumeric: Pertaining to a character set that contains letters, digits, and usually

other characters such as punctuation marks.

Anomaly: (IEEE) anything observed in the documentation or operation of software

that deviates from expectations based on previously verified software products or

reference documents. See: bug, defect, error, exception, fault.

1.6LEARNINGACTIVITY

18

CU IDOL SELF LEARNING MATERIAL (SLM)

1. Write a program in C++ to print a welcome text in a separate line.

__________________________________________________________________________

__________________________________________________________________________

2. Write a C++ program to compute the sum of the two given integer values. If the two

values are the same, then return triples their sum.

1.7 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive TypesQuestions

1. Outline the essential steps involved in carrying out a procedure-oriented programming

study.

2. Identify programming language where the problem to be solved is treated as a sequence

of steps? Discuss with its advantages.

3. Identify the programming where considering data as a critical element and do not allow it

to flow freely around the program? Correlate with this procedural programming.

4. Identify independent entities which provide easy development and maintenance of a

program correlate with function?

5. Identify data type with giving example which just specifies the structure of data?

B.Multiple Choice Questions

1. How structures and classes in C++ differ?

(a) In Structures, members are public by default whereas, in Classes, they are private by

default

(b) In Structures, members are private by default whereas, in Classes, they are public by

19

CU IDOL SELF LEARNING MATERIAL (SLM)

default

(c) Structures by default hide every member whereas classes do not

(d) Structures cannot have private members whereas classes can have

2. What does polymorphism in OOPs mean?

(a) Concept of allowing overriding of functions

(b) Concept of hiding data

(c) Concept of keeping things in different modules/files

(d) Concept of wrapping things into a single unit

3. C++ is ______________

(a) procedural programming language

(b) object-oriented programming language

(c) functional programming language

(d) both procedural and object-oriented programming language

4. What does modularity mean?

(a) Hiding part of program

(b) Subdividing program into small independent parts

(c) Overriding parts of program

(d) Wrapping things into single unit

5. Who invented OOP?

(a) Alan Kay

(b) Andrea Ferro

(c) Dennis Ritchie

Answers

1. (a), 2. (a), 3. (d), 4. (b) 5. (a)

1.8 REFERENCES

20

CU IDOL SELF LEARNING MATERIAL (SLM)

Balagurusamy E. (2001). Object Oriented Programming with C++. New Delhi: Tata

McGraw- Hill.

Lafore R. (2002). Object Oriented Programming in Turbo C+ +. USA: Sams

Publishing.

Schildt H. (2002). The Complete Reference in C++. New Delhi: TMH.

Kamthane (2003). Object Oriented Programming Using C++. New Delhi: Pearson

Education.

http://en.wikipedia.org/wiki/Object-oriented_programming

http://www.aonaware.com/OOP1.htm

http://www.stroustrup.com/C++11FAQ.html

Lack of Black OOPS: Kobe Bryant and the difficult path of redemption

DJ Leonard, CR King - Journal of Sport and Social Issues, 2011

21

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 2 FUNDAMENTALS OF C++ 2

Structure

2.0 LearningObjectives

2.1 Introduction

2.2 Data types

2.3 Input and output stream (Cin, Cout)

2.4 Introduction to namespace

2.5 Summary

2.6 KeyWords/Abbreviations

2.7 LearningActivity

2.8 Unit End Questions (MCQ andDescriptive)

2.9 References

2.0LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize Data types

DemonstrateInput and output stream (Cin, Cout)

Explain namespace

22

CU IDOL SELF LEARNING MATERIAL (SLM)

2.1INTRODUCTION

The prime purpose of C++ programming was to add object orientation to the C

programming language, which is in it one of the most powerful programming languages.The

core of the pure object-oriented programming is to create an object, in code, that has certain

properties and methods. While designing C++ modules, we try to see whole world in the

form of objects. For example a car is an object which has certain properties such as color,

number of doors, and the like. It also has certain methods such as accelerate, brake, and so

on. While writing program in any language, you need to use various variables to store

various information. Variables are nothing but reserved memory locations to store values.

This means that when you create a variable you reserve some space in memory.You may

like to store information of various data types like character, wide character, integer, floating

point, double floating point, Boolean etc. Based on the data type of a variable, the operating

system allocates memory and decides what can be stored in the reserved memory.While

doing programming inane programming language e, you need to use various variables to

store various information. Variables are nothing but reserved memory locations to store

values. This means that when you create a variable you reserve some space in memory. You

may like to store information of various data types like character, wide character, integer,

floating point, double floating point, boolean etc. Based on the data type of a variable, the

operating system allocates memory and decides what cane stored in the reserved memory

2.2 DATA TYPES

C++ offer the programmer a rich assortment of built-in as well as user defined data types.

Following table lists down seven basic C++ data types:

Table 2.1 Primitive Built-in Types

Type Keyword

Boolean bool

Character char

23

CU IDOL SELF LEARNING MATERIAL (SLM)

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers −

signed

unsigned

short

long

The following table shows the variable type, how much memory it takes to store the value in

memory, and what is maximum and minimum value which can be stored in such type of

variables.

Table 2.2 variable type

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

24

CU IDOL SELF LEARNING MATERIAL (SLM)

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 8bytes -2,147,483,648 to 2,147,483,647

signed long int 8bytes same as long int

unsigned long int 8bytes 0 to 4,294,967,295

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615

float 4bytes …..

25

CU IDOL SELF LEARNING MATERIAL (SLM)

double 8bytes …….

long double 12bytes ……

wchar_t 2 or 4 bytes 1 wide character

The size of variables might be different from those shown in the above table, depending on

the compiler and the computer you are using.

Following is the example, which will produce correct size of various data types on your

computer.

#include<iostream>

usingnamespace std;

int main(){

cout <<"Size of char : "<<sizeof(char)<< endl;

cout <<"Size of int : "<<sizeof(int)<< endl;

cout <<"Size of short int : "<<sizeof(shortint)<< endl;

cout <<"Size of long int : "<<sizeof(longint)<< endl;

cout <<"Size of float : "<<sizeof(float)<< endl;

cout <<"Size of double : "<<sizeof(double)<< endl;

cout <<"Size of wchar_t : "<<sizeof(wchar_t)<< endl;

return0;

}

This example uses endl, which inserts a new-line character after every line and << operator

26

CU IDOL SELF LEARNING MATERIAL (SLM)

is being used to pass multiple values out to the screen. We are also using sizeof () operator to

get size of various data types. When the above code is compiled and executed, it produces

the following result which can vary from machine to machine −

Size of char:1

Size of int:4

Size of short in:2

Size of long int:4

Size of float:4

Size of double:8

Size of wchar_t:4

typedef Declarations

You can create a new name for an existing type using typedef. Following is the simple

syntax to define a new type using typedef −

typedef type newname;

For example, the following tells the compiler that feet is another name for int −

typedef int feet;

Now, the following declaration is perfectly legal and creates an integer variable called

distance −

feet distance;

Enumerated Types-

An enumerated type declares an optional type name and a set of zero or more identifiers that

can be used as values of the type. Each enumerator is a constant whose type is the

27

CU IDOL SELF LEARNING MATERIAL (SLM)

enumeration. Creating an enumeration requires the use of the keyword enum. The general

form of an enumeration type is −

enum enum-name { list of names } var-list;

Here, the enum-name is the enumeration's type name. The list of names is comma separated.

For example, the following code defines an enumeration of colors called colors and the

variable c of type color. Finally, c is assigned the value "blue".

enum color { red, green, blue } c;

c = blue;

By default, the value of the first name is 0, the second name has the value 1, and the third

has the value 2, and so on. But you can give a name, a specific value by adding an initializer.

For example, in the following enumeration, green will have the value 5.

enum color { red, green = 5, blue };

Here, blue will have a value of 6 because each name will be one greater than the one that

precedes it.

2.3 INPUT AND OUTPUT STREAM (CIN, COUT)

A stream is a source of sequence of bytes. A stream abstracts for input/output devices. It can

be tied up with any I/O device and I/O can be performed in a uniform way. The C++

iostream library is an object-oriented implementation of this abstraction. It has a source

(producer) of flow of bytes and a sink (consumer) of the bytes. The required classes for the

stream I/O are defined in different library header files. To use the I/O streams in a C++

program, one must include iostream.h header file in the program. This file defines the

required classes and provides the buffering. Instead of functions, the library provides

operators to carry out the I/O. Two of the Stream Operators are:

<<: Stream insertion for output.

>>: Stream extraction for input.

28

CU IDOL SELF LEARNING MATERIAL (SLM)

The following streams are created and opened automatically:

cin : Standard console input (keyboard). C

out : Standard console output (screen).

cprn : Standard printer (LPT1).

cerr : Standard error output (screen). clog : Standard log (screen). caux : Standard

auxiliary (screen)

C++ comes with libraries that provide us with many ways for performing input and output.

In C++ input and output are performed in the form of a sequence of bytes or more

commonly known as streams.

Input Stream: If the direction of flow of bytes is from the device (for example,

Keyboard) to the main memory then this process is called input.

Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory

to device (display screen) then this process is called output

Fig 2.1 Stream for input and output

29

CU IDOL SELF LEARNING MATERIAL (SLM)

The two keywords cout in C++ and cin in C++ are used very often for printing outputs and

taking inputs respectively. These two are the most basic methods of taking input and printing

output in C++. To use cin and cout in C++ one must include the header file iostream in the

program

Let us program use of cout,cin

#include <iostream>

using namespace std;

int main()

{

char sample[] = "GeeksforGeeks";

cout << sample << " - A computer science portal for

geeks";

return 0;

}

Output:

GeeksforGeeks - A computer science portal for geeks

In the above program the insertion operator (<<) inserts the value of the string

variable sample followed by the string “A computer science portal for geeks” in the standard

output stream cout which is then displayed on screen.

#include <iostream>

30

CU IDOL SELF LEARNING MATERIAL (SLM)

using namespace std;

int main()

{

int age;

cout << "Enter your age:";

cin >> age;

cout << "\nYour age is: " << age;

return 0;

}

Input:

18

Output:

Enter your age:

Your age is: 18

Header files available in C++ for Input/Output operations are:

iostream: iostream stands for standard input-output stream. This header file contains

definitions to objects like cin, cout, cerr etc.

iomanip: iomanip stands for input output manipulators. The methods declared in

these files are used for manipulating streams. This file contains definitions of setw,

setprecision, etc.

fstream: This header file mainly describes the file stream. This header file is used to

handle the data being read from a file as input or data being written into the file as

output.

31

CU IDOL SELF LEARNING MATERIAL (SLM)

2.4 INTRODUCTIONS TO NAMESPACE

Namespaces allow us to group named entities that otherwise would have global scope into

narrower scopes, giving them namespace scope. This allows organizing the elements of

programs into different logical scopes referred to by names. Namespace is a feature added in

C++ and not present in C.A namespace is a declarative region that provides a scope to the

identifiers (names of the types, function, variables etc.) inside it.Multiple namespace blocks

with the same name are allowed. All declarations within those blocks are declared in the

named scope. A namespace definition begins with the keyword namespace followed by the

namespace name as follows:

namespace namespace_name

{

int x, y; // code declarations where

// x and y are declared in

// namespace_name's scope

}

Namespace declarations appear only at global scope.

Namespace declarations can be nested within another namespace.

Namespace declarations don’t have access specifiers. (Public or private)

No need to give semicolon after the closing brace of definition of namespace.

We can split the definition of namespace over several units.

32

CU IDOL SELF LEARNING MATERIAL (SLM)

Consider following C++ program.

// A program to demonstrate need of namespace

int main ()

{

int value;

value = 0;

double value; // Error here

value = 0.0;

}

Output:

Compiler Error:

'value' has a previous declaration as 'int value'

In each scope, a name can only represent one entity. So, there cannot be two

variables with the same name in the same scope. Using namespaces, we can create

two variables or member functions having the same name

Classes and Namespace:

Following is a simple way to create classes in a name space

// A C++ program to demonstrate use of class

// in a namespace

#include <iostream>

using namespace std;

33

CU IDOL SELF LEARNING MATERIAL (SLM)

namespace ns

{

// A Class in a namespace

class geek

{

public:

void display()

{

cout << "ns::geek::display()\n";

}

};

}

int main()

{

// Creating Object of geek Class

ns::geek obj;

obj.display();

return 0;

}

Output:

34

CU IDOL SELF LEARNING MATERIAL (SLM)

ns::geek::display ()

Example -Outside Namespace

// A C++ code to demonstrate that we can define

// methods outside namespace.

#include <iostream>

using namespace std;

// Creating a namespace

namespace ns

{

void display();

class geek

{

public:

void display();

};

}

// Defining methods of namespace

void ns::geek::display()

{

cout << "ns::geek::display()\n";

35

CU IDOL SELF LEARNING MATERIAL (SLM)

}

void ns::display()

{

cout << "ns::display()\n";

}

// Driver code

int main()

{

ns::geek obj;

ns::display();

obj.display();

return 0;

}

Output:

ns::display()

ns::geek::display ()

How to Use Namespaces

A supplier, say a library vendor, will present an interface to a set of services in the form of a

namespace. For example:

namespace my_library {

// classes

36

CU IDOL SELF LEARNING MATERIAL (SLM)

// typedefs

// global variable declarations

// templates

// global function declarations

// consts

// inline functions

// etc.

}

Typically, this will be placed in a header file so that a user includes the namespace like this:

#include "my_library.h"

// use my_library

To access the library facilities, the user has several choices. One can crudely and effectively

make all the names from the library available in the global scope:

#include "my_library.h" using namespace

my_library;

This is equivalent to a traditional #include of a header file that doesn’t use name spaces.

After

using namespace my_library;

every name from my_library is available without qualification. If used, a name from

my_library that clash with a global name cause a compile-time error unless the clash is

resolved by the function and operator overloading rules. Overload resolution applies across

namespaces where using-directives or using-declarations have made names accessible. A

more selective approach will be taken by users who worry about name clashes, about

function name resolution, or about documenting which facilities from my_library are

37

CU IDOL SELF LEARNING MATERIAL (SLM)

used. For example:

2.5 SUMMARY

C++ accomplishes input/output operations using concept of stream. A stream is a

series of bytes whose value depends on the variable in which it is stored.

This way, C++ is able to treat all the input and output operations in a uniform

manner. Thus, whether it is reading from a file or from the keyboard, for a C++

program it is simply a stream.

A stream is a source of sequence of bytes.

A stream abstracts for input/output devices. It can be tied up with any I/O device and

I/O can be performed in a uniform way.

The C++ iostream library is an object-oriented implementation of this abstraction.

It has a source (producer) of flow of bytes and a sink (consumer) of the bytes.

The required classes for the stream I/O are defined in different library header files.

Streams can also be tied up with data files.

38

CU IDOL SELF LEARNING MATERIAL (SLM)

Namespaces allow us to group named entities that otherwise would have global

scope into narrower scopes, giving them namespace scope. This allows organizing

the elements of programs into different logical scopes referred to by names.

Namespace is a feature added in C++ and not present in C.

A namespace is a declarative region that provides a scope to the identifiers (names of

the types, function, variables etc.) inside it.

While doing programming in any programming language, youneed to use various

variables to store various information. Variables are nothing but reserved memory

locations to store values. This means that whenyou create a variable you reserve

some space inmemory

C++ offer the programmer a rich assortment of built-in as well as user defined data

types.

Data types in C++ are categorized in three groups: Built-in, user-

defined and Derived.

2.6KEY WORDS/ABBREVIATIONS

C++ iostream Library: The C++ iostream library is an object-oriented

implementation of this abstraction.

Stream: A stream is a series of bytes whose value depends on the variable in which

it is stored.

Unformatted Input/output: Unformatted input/output is the simplest and most

efficient form of input/output.

chart: char keyword is used to declare a variable that can hold unsigned 16-bit

Unicode characters

39

CU IDOL SELF LEARNING MATERIAL (SLM)

Class: class keyword is used to declare a class.

Continue: continue keyword is used to continue the loop. It continues the current

flow of the program and skips the remaining code at the specified condition.

2.7LEARNINGACTIVITY

1.Assuming there are 7.481 gallons in a cubic foot, write a program that asks the user to

enter a number of gallons, and then displays the equivalent in cubic feet

__________________________________________________________________________

__________________________________________________________________________

2. Write a program define circumference of circle with radius 2.5

__________________________________________________________________________

__________________________________________________________________________

2.7UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. Constructs C++ program that outputs the following text on screen: Oh what a happy

day! Oh yes, what a happy day!

2. The following program contains several errors: Resolve the errors and run the

program to test your changes.

40

CU IDOL SELF LEARNING MATERIAL (SLM)

3.Construct to print all natural numbers up to N without using semi-colon.

4.State and construct program To Swap the values of two variables without using any extra

variable.

5.Identify feature which is used in C++ which declares that provides a scope to the

identifiers (names of the types, function, variables etc).Illustrate with example.

B. Multiple Choice Questions

1. Which keyword is used to define the user defined data types?

(a) Def

(b) Union

(c) Typedef

(d) type

2. Identify the correct statement.

(a) typedef does not create different types. It only creates synonyms of existing types

(b) typedef create different types

(c) typedef create own types

(d) typedef will not create synonyms of existing types

3. Where does a cin stops it extraction of data?

41

CU IDOL SELF LEARNING MATERIAL (SLM)

(a) By seeing a blank space

(b) By seeing (

(c) By seeing a blank space & (

(d) By seeing <

4. Which is used to get the input during runtime?

(a) Cout

(b) Cin

(c) Coi

(d) cinout

5. When will the cin can start processing of input?

(a) After pressing return key

(b) BY pressing blank space

(c) After pressing return key & BY pressing blank space

(d) BY pressing delete space

Answers

1. (c), 2. (a), 3. (a), 4. (b), 5. (a)

2.8REFERENCES

Venugopal, K.R. (2013), Rajkumar, Mastering C++. Tata McGraw-Hill Education

Rumbaugh J., Blaha M., Premerlani W., Eddy F., and Lorensen W., Object-oriented

Modeling and Design, Prentice-Hall, 1991.

Bolshakova E., Programming Paradigms in Computer Science Education,

International Journal: Information Theory & Applications, 12(3), 2005

42

CU IDOL SELF LEARNING MATERIAL (SLM)

Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill. Object Oriented

Programming with C++; Cyber tech publications.

http://www.cplusplus.com/reference/iostream/

http://www.cplusplus.com/reference/iostream/istream/getline/

https://developerinsider.co/introduction-to-cpp-cpp-programming/

An Overview of the C++ Programming Language January 1998 Bjarne Stroustrup

Programming with C++ concepts Jaakko Järvi a

Thinking in C++, Volume 1, 2nd Edition Completed January 13, 2000 Bruce Eckel,

43

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 3 - CLASSES AND OBJECTS 1

Structure

3.0 LearningObjectives

3.1 Introduction

3.2 Specifying a class

3.3 Creating objects

3.3.1 Objects as Function Arguments

3.3.2 Returning Objects

3.4 Accessing classes members

3.5 Defining a member function inside and outside classes

3.6 Access Specifier

3.6.1 The Public Access Specifier

3.6.2 The Private Access Specifier

3.6.3 The Protected Access Specifier

3.7 Summary

3.8 KeyWords/Abbreviations

3.9 LearningActivity

3.10 Unit End Questions (MCQ andDescriptive)

3.11 References

44

CU IDOL SELF LEARNING MATERIAL (SLM)

3.0LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize how to specify a class

Define the member functions

Explain the creation of class objects

Access the class members

Discuss the access specifiers

3.1INTRODUCTION

Classes and objects are at the core of object-oriented programming. Writing programs in

C++ essentially means writing classes and creating objects from them. In this unit you will

learn to work with the same. It is important to note the subtle differences between a class

and an object, here. A class is a template that specifies different aspects of the object it

models. It has no physical existence. It occupies no memory. It only defines various

members (data and/or methods) that constitute the class. An object, on the other hand, is an

instance of a class. It has physical existence and hence occupies memory. You can create as

many objects from a class once you have defined a class.You can think of a class as a data

type; and it behaves like one. Just as a data type like int, for Notes example, does not have a

physical existence and does not occupy any memory until a variable of that type is declared

or created; a class also does not exist physically and occupies no memory until an object of

that class is created.Example: To understand the difference clearly, consider a class of

vehicle and a few objects of this type as depicted below:

45

CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 3.1 example illustrating class

In this example vehicle is a class while car, scooter and truck are instances of the class

vehicle and hence are objects of vehicle class. Each instance of the class vehicle – car,

scooter and truck – are allocated individual memory spaces for the variables – reg_no,

no_wheels, fuel_type, make and, color – so that they all have their own copies of these

variables

3.2 SPECIFYING A CLASS

Like structures a class is just another derived data-type. While structure is a group of

elements of different data-type, class is a group of elements of different data-types and

functions that operate on them. C++ structure can also have functions defined in it. There is

very little syntactical difference between structures and classes in C++ and, therefore, they

can be used interchangeably with minor modifications. Since class is a specially introduced

data-type in C++, most of the C++ programmers tend to use the structures for holding only

data, and classes to hold both the data and functions. A class is a way to bind the data and its

associated functions together. It allows the data (and functions) to be hidden, if necessary,

from external use. When defining a class, we are creating a new abstract data-type that can

46

CU IDOL SELF LEARNING MATERIAL (SLM)

be treated like any other built-in data-type. Generally, a class specification has two parts:

1. Class declaration

2. Class function definitions

The class declaration describes the type and scope of its members. The class function

definitions describe how the class functions are implemented. The general form of a class

declaration is:

class

{

private:

variables declaration;

function declarations;

public:

variable declaration;

function declarations;

};

The class declaration is similar to a struct declaration. The keyword class specifies that what

follows is an abstract data of type class_name. The body of a class is enclosed within braces

and terminated by a semicolon. The class body contains the declaration of variables and

functions. These functions and variables are collectively called members. They are usually

grouped under two sections, namely, private and public to denote which of the members are

private and which of them are public. The keywords private and public are known as

visibility labels. The members that have been declared as private can be accessed only from

within the class. On the other hand, public members can be accessed from outside the class

also. The data hiding (using private declaration) is the key feature of object-oriented

47

CU IDOL SELF LEARNING MATERIAL (SLM)

programming. The use of the keyword private is optional. By default, the members of a class

are private. If both the labels are missing, then, by default, all the members are private. Such

a class is completely hidden from the outside world and does not serve any purpose.

Fig 3.2 Data Assess in Class

The variables declared inside a class are known as data members and the functions are

known as member functions. Only the member functions can have access to the private data

members and private functions. However, the public members (both functions and data) can

be accessed from Notes outside the class. The binding of data and functions together into a

single class-type variable is referred to as encapsulation. The access to private and public

members of a class is well explained diagrammatically in the Figure 3.1 Let us consider the

following declaration of a class for student:

48

CU IDOL SELF LEARNING MATERIAL (SLM)

The name of the class is student. With the help of this new type identifier, we can declare

instances of class student. The data members of this class are int rollno and char name [20].

The two function members are getdata () and disp(). Only these functions can access the data

members. Therefore, they provide the only access to the data members from outside the

class. The data members are usually declared as private and member functions as public.

The member functions are only declared in the class. They shall be defined later.A class

declaration for a machine may be as follows:

Having defined the class, we need to create object of this class. In general, a class is a user

defined data type, while an object is an instance of a class. A class provides a template,

which defines the member functions and variable that are required for objects of a class type.

A class must be defined prior to the class declaration. The general syntax for defining the

object of a class is:

49

CU IDOL SELF LEARNING MATERIAL (SLM)

The general syntax for defining the object of a class is:

Class

{

A class definition is very similar to a structure definition except the class definition defines

the variables and functions. Consider the following program segment which declares and

creates a class of objects.

50

CU IDOL SELF LEARNING MATERIAL (SLM)

student std; //std is the object of the class student

In another example the employee details such as name. code, designation, address, salary

age can be grouped as follows.

The only difference between defining a class member function completely within its class or

to include only the prototype and later its definition, is that in the first case the function will

automatically be considered an inline member function by the compiler, while in the second

it will be a normal (not-inline) class member function, which in fact supposes no difference

in behavior.

51

CU IDOL SELF LEARNING MATERIAL (SLM)

3.2 DEFINING MEMBER FUNCTIONS

We have learnt to declare member functions. Let us see how member functions of a class

can be defined within a class or outside a class. A member function is defined outside the

class using the: (double colon symbol) scope resolution operator. The general syntax of the

member function of a class outside its scope is:

< class_name>:: (arg1, arg2....argN)

The type of member function arguments must exactly match with the types declared in the

class definition of the . The Scope resolution operator (::) is used along with the class name

in the header of the function definition. It identifies the function as a member of a particular

class. Without this scope operator the function definition would create an ordinary function,

subject to the usual function rules of access and scope. The following program segment

shows how a member function is declared outside the class declaration.

Let us consider the following program snippet:

52

CU IDOL SELF LEARNING MATERIAL (SLM)

Both classes in the above case are defined with the same member function names. While

accessing this member function, it gives an error. The scope of the member function sum( )

is not defined. When accessing the member function sum( ), control will be transferred to

53

CU IDOL SELF LEARNING MATERIAL (SLM)

both classes one and two. So the scope resolution operator (::) is absolutely necessary for

defining the member functions outside the class declaration

3.3 CREATING CLASS OBJECTS

Objects are the basic run-time entities in an object-oriented system. They may represent a

person, a place, a bank account, a table of data; they may also represent user-defined data

such as vectors, time and lists.

Fig 3.3Example of an Object

They occupy space in memory that keeps its state and is operated on by the defined

operations on the object. Each object contains data and code to manipulate the data. Objects

can interact without having to know details of each other data or code.

3.3.1 Objects as Function Arguments

54

CU IDOL SELF LEARNING MATERIAL (SLM)

Like any other data type argument, objects can also be passed to a function. As you know

arguments are passed to a function in two ways:

1. by value

2. by reference

Objects can also be passed as arguments to the function in these two ways. In the first

method, a copy of the object is passed to the function. Any modification made to the object

in the function does not affect the object used to call the function. The following Program

illustrates the calling of functions by value. The program declares a class integer

representing an integer variable x. Only the values of the objects are passed to the function

written to swap them.

55

CU IDOL SELF LEARNING MATERIAL (SLM)

You should get the following output.

enter a value for x 15

enter a value for x 50

the value of x belonging to object int is 15

the value of x belonging to object int2 is 50

after swapping

The value of x belonging to object int is 15 the value of x belonging to object int2 is 50

In the second method, the address of the object is passed to the function instead of a copy of

the object. The called function directly makes changes on the actual object used in the call.

As against the first method any manipulations made on the object inside the function will

occur in the actual object.

56

CU IDOL SELF LEARNING MATERIAL (SLM)

The following Program illustrates calling of a function by reference. The program declares a

class integer to represent the variable x and defines functions to input and display the value.

The function written to swap the integer values of the object takes the addresses of the

objects.

57

CU IDOL SELF LEARNING MATERIAL (SLM)

You should see the following output.

Enter a value for x 15

Enter a value for x 50

the value of x belonging to object int1 is 15

the value of x belonging to object int2 is 50

after swapping

the value of x belonging to object int1 is 50

the value of x belonging to object int2 is 15

3.3.2 Returning Objects

Just as a function takes an object as its argument, it can also return an object. The following

program illustrates how objects are returned. The program declares a class integer

representing an integer variable x and defines a function to calculate the sum of two integer

58

CU IDOL SELF LEARNING MATERIAL (SLM)

values. This function finally returns an object which stores the sum in its data member x.

59

CU IDOL SELF LEARNING MATERIAL (SLM)

You should see the following output from the program.

the value of x for object int1 15

the value of x for object int2 25

the sum of private data values of x belonging to objects int1 and int2 is 40

3.4 ACCESSING A MEMBER OF CLASS

Member data items of a class can be static. Static data members are data objects that are

common to all objects of a class. They exist only once in all objects of this class. The static

members are used when the information is to be shared. They can be public or private data.

The main advantage of using a static member is to declare the global data which should be

updated while the program lives in memory. When a static member is declared private, the

non-member functions cannot access these members. But a public static member can be

accessed by any member of the class. The static data member should be created and

initialized before the main function control block begins.

60

CU IDOL SELF LEARNING MATERIAL (SLM)

The static variable balance is initialized outside main () as follows:

int account::balance = 0; //static data definition

The static variable balance is initialized outside main() as follows: int account::balance = 0;

//static data definition Consider the following Program which demonstrates the use of static

data member count. The variable count is declared static in the class but initialized to 0

outside the class.

61

CU IDOL SELF LEARNING MATERIAL (SLM)

}

You should get the following output from this program.

The present value of count is 1

The present value of count is 2

The present value of count is 3

The present value of count is 4

62

CU IDOL SELF LEARNING MATERIAL (SLM)

The present value of count is 5

3.5 ACCESS SPECIFIERS

Members of a class can access other members (properties and methods) of the same class.

Functions, operators and other classes (corresponding objects) outside the class description

of a particular class can also access members of that class. An access specifier decides

whether or not a function or operator or class, outside the class description can access the

members it controls inside its class description. The members an access specifier controls

are the members typed under it in the class description (until the next specifier). We will use

functions and classes in the illustrations of accesses to class members. We will not use

operators for the illustrations. We will be using the phrase, external function. This refers to a

function or class method that is not a member of the class description in question. When we

say an external function can access a class member, we mean the external function can use

the name (identifier of property or name of method) of the member as its argument or as an

identifier inside its definition.

3.5.1 The Public Access Specifier

With the public access specifier, an external function can access the public members of the

class. The following code illustrates this (read the explanation below):

63

CU IDOL SELF LEARNING MATERIAL (SLM)

There are two functions in the code: myFn() and main(). The first line in the main function

instantiates a class object called, obj. In main, lines 2 and 3 use the properties of the class as

identifiers. Because the class members are public, the main() function can access the

members of the class. Line 4 of the main function also demonstrates this. In line 6 of the

main function, the function, myFn() uses the property num1 of the class as its argument. It

64

CU IDOL SELF LEARNING MATERIAL (SLM)

could do so because the member, num1 is public in the class.

3.5.2 The Private Access Specifier

With the private access specifier an external function cannot access the private members of

the class. With the private specifier only a member of a class can access the private member

of the class. The following code shows how only a member of a class can access a private

member of the class (read the explanation below)

65

CU IDOL SELF LEARNING MATERIAL (SLM)

The class has two private members (properties) and one public member (method). In the

class description, the add () method uses the names of the private members as identifiers. So,

the add () method, a member of the class has accessed the private members of the class. The

main function definition (second line) has been able to access the add () method of the class

because the add () method is public (it has a public access specifier). The following code

will not compile because the main function tries to access (use as identifier) a private

member of the class:

66

CU IDOL SELF LEARNING MATERIAL (SLM)

The second line in the main function is wrong because at that line, main tries to access (use

as identifier) the private member, num1.

3.5.3 The Protected Access Specifier

If a member of a class is public, it can be accessed by an external function including a

derived class. If a member of a class is private, it cannot be accessed by an external function;

67

CU IDOL SELF LEARNING MATERIAL (SLM)

even a derived class cannot access it. The question is, should a derived class not really be

able to access a private member of its base class (since the derived class and base class are

related)? Well, to solve this problem you have another access specifier called, protected. If a

member of a class is protected, it can be accessed by a derived class, but it cannot be

accessed by an external function. It can also be accessed by members within the class. The

following code illustrates how a derived class can access a protected member of a base class:

68

CU IDOL SELF LEARNING MATERIAL (SLM)

The base class has just two properties and no method; these properties are protected. The

derived class has one method and no property. Inside the derived class, the protected

properties of the base class are used as identifiers. Generally, when a derived class is using a

member of a base class, it is a method of the derived class that is using the member, as in

this example. The above code is OK. The following code will not compile, because line 2 in

the main () function tries to access a protected member of the base class:

69

CU IDOL SELF LEARNING MATERIAL (SLM)

70

CU IDOL SELF LEARNING MATERIAL (SLM)

An external function cannot access a protected member of a class (base class); however, a

derived class method can access a protected member of the base class.You should now know

the role of the access specifiers: public, protected and private as applied to classes. In one of

the following parts of the series, we shall see the role of the access specifiers in the

declarator of a derived class. A public member of a class is accessible by external functions

and a derived class. A private member of a class is accessible only by other members of the

class; it is not accessible by external functions and it is not accessible by a derived class. A

protected member of a class is accessible by a derived class (and other members of the

class); it is not accessible by an external function

3.6 SUMMARY

A class represents a group of similar objects. A class in C++ binds data and

associated functions together.

It makes a data type using which objects of this type can be created. Classes can

represent the real-world object which have characteristics and associated behavior.

While declaring a class, four attributes are declared: data members, member

functions, program access levels (private, public, and protected,) and class tag name.

While defining a class its member functions can be either defined within the class

definition or outside the class definition. The public member of a class can be

accessed outside the class directly by using object of this class type.

Private and protected members can be accessed with in the class by the member

function only. The member function of a class is also called a method. The qualified

name of a class member is a class name:: class member name.

A global object can be declared only from a global class whereas a local object can

be declared from a global as well as a local class.

71

CU IDOL SELF LEARNING MATERIAL (SLM)

The object is created separately to store their data members. They can be passed to

as well as returned from functions. The ordinary members functions can access both

static as well as ordinary member of a class.

The classes are the most important feature of C++ that leads to Object Oriented

programming. Class is a user defined data type, which holds its own data members

and member functions, which can be accessed and used by creating instance of that

class.

The variables inside class definition are called as data members and the functions are

called member functions.

Attributes and methods are basically variables and functions that belongs to the class.

These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works as an

object constructor, or a "blueprint" for creating objects.

3.7 KEYWORDS

Class: Represents the real-world objects which have characteristics and associated

behavior.

Global Class: A class whose definition occurs outside the bodies of all functions in a

program. Objects of this class type can be declared from anywhere in the program.

Local Class: A class whose definition occurs inside a function body. Objects of this

class type can be declared only within the function that defines this class type.

Private Members: Class members that are hidden from the outside world. Public

Members: Class members (data members and member functions) that can be used by

any function.

Temporary Object: An anonymous short lived object.

Declaration: The introduction of a name (identifier) into a scope

72

CU IDOL SELF LEARNING MATERIAL (SLM)

Compiler: A program that translates high-level source code, e.g., C++, into low-

level machine language. Some compilers output assembly language which is then

converted to machine language by a separate assembler. A compiler must first

separate the statements of the source code from one another before it can translate

them. Each statement must then be translated by evaluating its expressions according

to the grammar. Both of these steps use parsing.

Scope: The source code extending from a declaration up until the end of

the block which contains the declaration

3.8 LEARNINGACTIVITY

1. Write a C+ + program to find out the sum of n numbers.

__________________________________________________________________________

__________________________________________________________________________

2. Write a program which illustrates the declaration of the class Employee with the

operations on its object

__________________________________________________________________________

_______________________________________________________________________

73

CU IDOL SELF LEARNING MATERIAL (SLM)

3.9 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. “The main advantage of using a static member is to declare the global data which should

be updated while the program lives in memory”. Justify your statement.

2. Write a program to print the score board of a cricket match in real time. The display

should contain the batsman’s name, runs scored, indication if out, mode by which out,

bowler’s score (overs played, maiden overs, runs given, wickets taken). As and when a

ball is thrown, the score should be updated.

3. If a member of a class is public, it can be accessed by an external function including a

derived class. Explain with an example.

4. Implement a program in which a class has one private member (properties) and two

public member (method).

5. The program on the opposite page contains several errors! Correct the errors and ensure

that the program can be executed.

B. Multiple Choice Questions

1. Which among the following best describes member functions?

(a) Functions which are defined within the class

(b) Functions belonging a class

(c) Functions in public access of a class

(d) Functions which are private to class

2. How many types of member functions are generally there in C++?

(a) 2

(b) 3

74

CU IDOL SELF LEARNING MATERIAL (SLM)

(c) 4

(d) 5

3. How can a static member function be called in the main function?

(a) Using dot operator

(b) Using arrow operator

(c) Using dot or arrow operator

(d) Using dot, arrow or using scope resolution operator with class name

4. What are inline member functions?

(a) Member functions which can be called without object

(b) Member functions whose definition is expanded in place of its call

(c) Member functions whose definition is faster than simple function

(d) Member function which is defined in single line

5. What happens if non-static members are used in static member function?

(a) Compile time error

(b) Runtime error

(c) Executes fine

(d) Executes if that member function is not used

Answers

1. (b), 2. (d), 3. (d), 4. (b), 5. (a)

3.10REFERENCES

Accelerated C++: Practical Programming by Example by Andrew Koenig and

Barbara E. Moo

75

CU IDOL SELF LEARNING MATERIAL (SLM)

effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14

(1st Edition) by Scott Meyers

Data Structures and Algorithms Made Easy by Narasimha Karumanchi

Burden R.L., Douglas Faires J., Numerical Analysis, Brooks/Cole, 2001

Freberg C.E., Introduction to Numerical Analysis, Addison Wesley, 1969.

http://msdn.microsoft.com/en-us/library/h05xxt5d(v=vs.80).aspx

http://www.cplusplus.com/forum/beginner/6713/

https://www.studytonight.com/cpp/introduction-to-cpp.php

Implementing Object-Oriented Features In C++,Software Development with C++

Maximizing Reuse with Object Technology1995, Pages 319-353

An object‐oriented class library for C++ programs Keith E. Gorlen

76

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 4 CLASSES AND OBJECTS 2

Structure

4.0 Learningobjectives

4.1 Introduction

4.2 Inline functions

4.3 Static data members

4.4 Member functions

4.5 Objects as function argument

4.6 Friend function

4.6.1 Friend Function in Empty Classes

4.6.2 Friend Function in Nested Classes

4.6.3 Friend Function in Local Classes

4.7 Summary

4.8 Keywords/abbreviations

4.9 Learningactivity

4.10 Unit end questions (mcq anddescriptive)

4.11 References

4.0LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize the static members

Describe the const and class keyword

77

CU IDOL SELF LEARNING MATERIAL (SLM)

Explain the static objects

Discuss the friend function

Discuss Inline functions

4.1 INTRODUCTION

A class in C++ is the building block that leads to Object-Oriented programming. It is a user-

defined data type, which holds its own data members and member functions, which can be

accessed and used by creating an instance of that class. A C++ class is like a blueprint for an

object. For Example: Consider the Class of Cars. There may be many cars with different

names and brand but all of them will share some common properties like all of them will

have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed

limits, mileage are their properties. An Object is an instance of a Class. When a class is

defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory

is allocated. In this section, we will discuss the static members. The members of a class can

be made static (data member and function member both). Can you tell, what is static? Well,

static is a storage class specifier/qualifier that provides information about locality and

visibility of variables. Let us discuss the static data member. Sometimes, we need to have

one or more common data member, which are accessible to all objects of a class. For

example, we need to keep the status as to how many objects of a class are created and how

many of them are currently active in the program. In such situation, and many others, C++

provides static data member. Static data member is initialized to zero when the first object of

its class is created. No other initialization is permitted. A variable that is part of a class, yet

is not the part of an object of that class, is called a static data member. There is exactly one

copy of static data member instead of one copy per object, as for ordinary non-static data

members.Static data members of a class in namespace scope have external linkage. Static

data members follow the usual class access rules, except that they can be initialized in file

scope. Static data members and their initializes can access other static private and protected

78

CU IDOL SELF LEARNING MATERIAL (SLM)

members of their class. The initialize for a static data member is in the scope of the class

declaring the member. A friend function is a function that is not a member of a class but has

access to the class’s private and protected members.

4.2 INLINE FUNCTION

C++ provides facility of inline function, which is designed to speed up the program

execution. This is done by the C++ compiler, which incorporates it into a program. When

any program is compiled the output of compilation is a set of machine language instructions,

which is in executable program. When a program is run, this complied copy of program is

put into memory. Each instruction gets a memory address, which is used to refer that

instruction. These instructions are executed as per the logic in the program. Instructions are

executed step by step unless there is any loop or branching instructions. When there is

branch or jump instruction, some instructions are skipped and forward or backward jump is

made. In normal function call, the control of execution is transferred to the location where

the function is loaded in memory that is the starting executable instruction of the function.

When all the instructions of the function are executed the control returns back to main

program from where left.Now the next instruction in the main program will get executed.

Jumping back and forth keeping track of where to jump means that there is an overhead in

elapsed time to functions. When the function is declared inline the compiler replaces the

function call with the corresponding function code. As a result the program does not have to

spend time to jump to another location to execute the function and then come back. But there

is a memory overhead. If the function is called n times in the program then it is copied n

times making the program code or in particular executable code large. If the value of n is

large, there is a lot of memory overhead.The following program demonstrates the use of

inline function to calculate square of an input number.

79

CU IDOL SELF LEARNING MATERIAL (SLM)

You should see the output as shown below.

Enter a number 1.2

The square of 1.2 is 1.44

Actually, compiler compiles the code by inserting the function definition at the place where

it is called as shown below.

80

CU IDOL SELF LEARNING MATERIAL (SLM)

4.3 STATIC DATA MEMBERS

Member data items of a class can be static. Static data members are data objects that are

common to all objects of a class. They exist only once in all objects of this class. The static

members are used when the information is to be shared. They can be public or private data.

The main advantage of using a static member is to declare the global data which should be

updated while the Notes program lives in memory. When a static member is declared

private, the non-member functions cannot access these members. But a public static member

can be accessed by any member of the class. The static data member should be created and

initialized before the main function control block begins. For example, consider the class

account as follows:

81

CU IDOL SELF LEARNING MATERIAL (SLM)

The static variable balance is initialized outside main() as follows:

int account::balance = 0; //static

Data definition Consider the following Program which demonstrates the use of static data

member count. The variable count is declared static in the class but initialized to 0 outside

the class.

82

CU IDOL SELF LEARNING MATERIAL (SLM)

You should get the following output from this program.

The present value of count is 1

The present value of count is 2

The present value of count is 3

The present value of count is 4

The present value of count is 5

A typical use of static members is for recording data common to all objects of a class. For

example, you can use a static data member as a counter to store the number of objects of a

83

CU IDOL SELF LEARNING MATERIAL (SLM)

particular class type that are created

4.4 STATIC MEMBER FUNCTIONS

Just as data members can be static, member functions can also be static. A static function is a

member function of a class and it manipulates only static data member of the class. It acts as

global for members of its class without affecting the rest of the program. Static members

serve the purpose of reducing the need for global variables by providing alternatives that are

local to a class. A static member function is not a part of objects of class. It is instance

dependent and can be accessed directly by using the class name and scope resolution

operator. If it is declared and defined in a class, the keyword static should be used only in

declaration part. The following program demonstrates the use of static member function

which accesses static data. The data member count and the function disp() are declared static

in the class counter. But the variable count is initialized to 0 outside the class.

84

CU IDOL SELF LEARNING MATERIAL (SLM)

You should get the following output on running the program.

85

CU IDOL SELF LEARNING MATERIAL (SLM)

Number of objects created before=0

Number of objects created recently=5

In defining static functions you should take some precautions. A static member functions

cannot be a virtual function.

4.5 OBJECTS AS FUNCTION ARGUMENT

As we know that, we can pass any type of arguments within the member function and there

are any numbers of arguments. In C++ programming language, we can also pass an object as

an argument within the member function of class. This is useful, when we want to initialize

all data members of an object with another object, we can pass objects and assign the values

of supplied object to the current object. For complex or large projects, we need to use

objects as an argument or parameter.

Consider the given program:

#include <iostream>

usingnamespace std;

class Demo

{

private:

int a

public:

void set(int x)

{

a = x;

86

CU IDOL SELF LEARNING MATERIAL (SLM)

}

void sum(Demo ob1, Demo ob2)

{

a = ob1.a + ob2.a;

}

void print()

{

cout<<"Value of A : "<<a<<endl;

}

};

int main()

{

//object declarations

Demo d1;

Demo d2;

Demo d3;

//assigning values to the data member of objects

d1.set(10);

d2.set(20);

//passing object d1 and d2

87

CU IDOL SELF LEARNING MATERIAL (SLM)

d3.sum(d1,d2);

//printing the values

d1.print();

d2.print();

d3.print();

return 0;

}

Output

Value of A : 10

Value of A : 20

Value of A : 30

Above example demonstrate the use of object as a parameter. We are

passing d1 and d2 objects as arguments to the sum member function and adding the value of

data members a of both objects and assigning to the current object’s (that will call the

function, which is d3 data member

4.6 FRIEND FUNCTION

Object oriented programming paradigm secures data because of the data hiding and data

encapsulation features. Data members declared as private in a class are restricted from

access by non-member functions. The private data values can be neither read nor written by

non-member functions. Any attempt made directly to access these members, will result in an

error message as “inaccessible data-type” during compilation. The best way to access a

private data member by a non-member function is to change a private data member to a

public group. But this goes against the concept of data hiding and data encapsulation. A

88

CU IDOL SELF LEARNING MATERIAL (SLM)

special mechanism available known as friend function allows non-member functions to

access private data. A friend function may be either declared or defined within the scope of a

class definition. The keyword friend informs the compiler that it is not a member function

nor the property of the class. The general syntax of the friend function is: friend (argument

list);

friend is a keyword. A friend declaration is valid only within or outside the class definition.

The following code snippet shows how a friend function is defined.

1. The friend function disp( ) is declared in the public group

89

CU IDOL SELF LEARNING MATERIAL (SLM)

2. The friend function disp( ) is declared in the private group

Since private data members are available only to the particular class and not to any other

part of the program, a non-member function cannot access these private data. Therefore, the

friend function is a special type of function which is used to access the private data of any

class. In other words, they are defined as non-member functions with the ability to modify

data directly or to call function members that are not part of the public interface. The friend

class has the right to access as many members of its class. As a result the level of privacy of

the data encapsulation gets reduced. Only if it is necessary to access the private data by non-

member functions, then a class may have a friend function, otherwise it is not necessary.Let

us look at a sample program given below to access the private data of a class by non-

member functions through friend function. The program declares a private class example

90

CU IDOL SELF LEARNING MATERIAL (SLM)

representing variable x and function to input the value for the same. The friend function to

display the value of x takes an object as argument with the help of which private variable x

can be accessed

You should see the following output.

Enter the value of x

91

CU IDOL SELF LEARNING MATERIAL (SLM)

4

Display the entered number 4

There are also other areas of application for friend function. The friend function can also be

defined within the scope of a class definition itself. Friend function may also have inline

member functions. If the friend function is defined in the class, then the inline code

substitution is done automatically. But if defined outside the class, then it is necessary to

precede the return type with the keyword inline to make the inline code substitution

4.6.1 Friend Function in Empty Classes

92

CU IDOL SELF LEARNING MATERIAL (SLM)

4.6.2 Friend Function in Nested Classes

Friend functions declared in a nested class are considered to be in the scope of the nested

class, not the enclosing class. Therefore, the friend functions gain no special access

privileges to members or member functions of the enclosing class. If you want to use a name

93

CU IDOL SELF LEARNING MATERIAL (SLM)

The preceding code shows the function GetExtendedErrorStatus declared as a friend

function. In the function, which is defined in file scope, a message is copied from a static

array into a class member. Note that a better implementation ofGetExtendedErrorStatus is to

declare it as: int GetExtendedErrorStatus(char *message ) With the preceding interface,

94

CU IDOL SELF LEARNING MATERIAL (SLM)

several classes can use the services of this function by passing a memory location where

they want the error message copied.

4.6.3 Friend Function in Local Classes

The name of a friend function or class first introduced in a friend declaration is not in the

scope of the class granting friendship (also called the enclosing class) and is not a member

of the class granting friendship. The name of a function first introduced in a friend

declaration is in the scope of the first nonclass scope that contains the enclosing class. The

body of a function provided in a friend declaration is handled in the same way as a member

function defined within a class. Processing of the definition does not start until the end of the

outermost enclosing class. In addition, unqualified names in the body of the function

definition are searched for starting from the class containing the function definition. If the

name of a friend class has been introduced before the friend declaration, the compiler

searches for a class name that matches the name of the friend class beginning at the scope of

the friend declaration. If the declaration of a nested class is followed by the declaration of a

friend class with the same name, the nested class is a friend of the enclosing class. The scope

of a friend class name is the first nonclass enclosing scope. For example:

95

CU IDOL SELF LEARNING MATERIAL (SLM)

4.7SUMMARY

Member data items of a class can be static. Static data members are data objects that

are common to all objects of a class.

They exist only once in all objects of this class.

The static members are used when the information is to be shared.

They can be public or private data. The main advantage of using a static member is

to declare the global data which should be updated while the program lives in

memory.

A static member function is not a part of objects of class.

It is instance dependent and can be accessed directly by using the class name and

scope resolution operator.

If it is declared and defined in a class, the keyword static should be used only in

declaration part.

The friend function is written as any other normal function, except the function

declaration of these functions is preceded with the keyword friend.

The friend function must have the class to which it is declared as friend passed to it

96

CU IDOL SELF LEARNING MATERIAL (SLM)

in argument.

Whenever an object of a class is passed to a member function of the same class, its

data members can be accessed inside the function using the object name and the dot

operator. However, the data members of the calling object can be directly accessed

inside the function without using the object name and the dot operator.

To pass an object as an argument we write the object name as the argument while

calling the function the same way we do it for other variables. Syntax:

function_name(object_name); Example: In this Example there is a class

which has an integer variable 'a' and a function 'add' which takes an object as

argument.

4.8 KEY WORDS/ABBREVIATIONS

Friend Function: A function which is not a member of a class but which is given

special permission to access private and protected members of the class.

Static Data Members: Static data members are data objects that are common to all

objects of a class.

Static Member Functions: Functions that can access only the static members.

Access declaration: a way of controlling access to a specified member of a base

class when it is used in a derived class.

Access specifier: a way of labeling members of a class to specify what access is

permitted.

4.9LEARNINGACTIVITY

1. WAP to implement friend function.

__________________________________________________________________________

97

CU IDOL SELF LEARNING MATERIAL (SLM)

__________________________________________________________________________

2. WAP to implement static data members

__________________________________________________________________________

__________________________________________________________________________

4.10UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. Should my class declare a member function or a friend function?” Do you agree with this

statement? Why or why not. Justify you answers with an example.

2. “A friend function is a function that can access the private members of a class as though

it were a member of that class”. Explain.

3. Write a program which is using the friend function in the nested classes and local classes.

4. Discuss why a friend function is used for accessing the non-public members of a class.

5. Justify Can we access private data members of a class without using a member or a friend

function?

B. Multiple Choice Questions

1. In C++ code, variables can be passed to a function by

(a)Pass by value

(b)Pass by reference

(c)Pass by pointer

(d)All the above

2. Constant function in C++ can be declared as

(a)Void display ()

98

CU IDOL SELF LEARNING MATERIAL (SLM)

(b)void display () const

(c)const void display ()

(d)void const display ()

3. Which of the following functions are provided by compiler by default if we don’t write in

a C++ class?

(a)Copy constructor

(b)Assignment

(c)Constructor

(d)All the above

4.Which function can be called without using an object of a class in C++

(a)Static function

(b)Inline function

(c)Friend function

(d)constant function

5. Which function can be called without using an object of a class in C++

(a)Virtual function

(b)Inline function

(c)Static function

(d)constant function

Answers

99

CU IDOL SELF LEARNING MATERIAL (SLM)

1. (d), 2. (b), 3. (d), 4. (a), 5. (c)

4.11REFERENCES

C++ Programming Language – By D. S. Malik

Object Oriented Concepts and Programming in C++ Lab Book – By Manisha

Suryavanshi, Madhuri Ghanekar, S. G. Lakhdive , Parag Tamhankar and Manisha

Jagdale

C++ Programming- A practical approach – By Madhusudan Mothe

http://en.wikipedia.org/wiki/Friend_function

http://www.cplusplus.com/doc/tutorial/functions/

http://cpp-tutorial.cpp4u.com/structures_functions.html

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/

com.ibm.xlcpp8a.doc/language/ref/cplr038.htm

Software Development with C++Maximizing Reuse with Object Technology 1995,

Pages 355-370

Selective friends in C++ May 2017 Software Practice and ExperienceGábor Márton

Static interfaces in C++ Brian McNamara and Yannis Smaragdakis Georgia Institute

of Technology

100

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 5CONSTRUCTORS AND DESTRUCTORS

Structure

5.0 LearningObjectives

5.1 Introduction

5.2 Need for Constructor and Destructor

5.2.1. Constructor

5.2.2. Destructor

5.3 Type of constructor

5.3.1 Default constructor

5.3.2 Parameterized constructor

5.3.3 Copy constructor

5.4 Destructors

5.5 Summary

5.6 KeyWords/Abbreviations

5.7 LearningActivity

5.8 Unit End Questions (MCQ andDescriptive)

5.9 References

5.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize the need for constructor and destructors

Describe the copy constructor

Explain the dynamic constructor

101

CU IDOL SELF LEARNING MATERIAL (SLM)

Discuss the destructors

5.1 INTRODUCTION

When an object is created all the members of the object are allocated memory spaces. Each

object has its individual copy of member variables. However the data members are not

initialized automatically. If left uninitialized these members contain garbage values.

Therefore it is important that the data members are initialized to meaningful values at the

time of object creation. Conventional methods of initializing data members have lot of

limitations. In this unit you will learn alternative and more elegant ways initializing data

members to initial values. When a C++ program runs it invariably creates certain objects in

the memory and when the program exits the objects must be destroyed so that the memory

could be reclaimed for further use. C++ provides mechanisms to cater to the above two

necessary activities through constructors and destructors methods.

5.2 NEED FOR CONSTRUCTOR AND DESTRUCTOR

5.2.1 Constructor

Constructor is public method that is called automatically when the object of a particular

class is created. C++ provides a default constructor method to all the classes. This

constructor method takes no parameters. Actually the default constructor method has been

defined in system.object class. Since every class that you create is an extension of

system.object class, this method is inherited by all the classes. The default constructor

method is called automatically at the time of creation of an object and does nothing more

than initializing the data variables of the object to valid initial values.

While writing a constructor function the following points must be kept in mind:

1. The name of constructor method must be the same as the class name in which it is

defined.

2. A constructor method must be a public method.

102

CU IDOL SELF LEARNING MATERIAL (SLM)

3. Constructor method does not return any value. 4. A constructor method may or may not

have parameters.

Let us examine a few classes for illustration purpose. The class abc as defined below does

not have user defined constructor method.

The main function above an object named myabc has been created which belongs to abc

class defined above. Since class abc does not have any constructor method, the default

constructor method of C++ will be called which will initialize the member variables as:

Let us now redefine myabc class and incorporate an explicit constructor method as shown

below:

The main function above an object named myabc has been created which belongs to abc

class defined above. Since class abc does not have any constructor method, the default

constructor method of C++ will be called which will initialize the member variables as:

103

CU IDOL SELF LEARNING MATERIAL (SLM)

Let us now redefine myabc class and incorporate an explicit constructor method as shown

below:

Observed that myabc class has now a constructor defined to except two parameters of

integer type. We can now create an object of myabc class passing two integer values for its

construction, as listed below:

In the main function myabc object is created value 100 is stored in data variable x and 200 is

stored in data variable y. There is another way of creating an object as shown below.

104

CU IDOL SELF LEARNING MATERIAL (SLM)

Both the syntaxes for creating the class are identical in effect. The choice is left to the

programmer. There are other possibilities as well. Consider the following class differentials:

In this class constructor has been defined to have no parameter. When an object of this class

is created the programmer does not have to pass any parameter and yet the data variables x,

yis initialized to 100 and 200 respectively.

Finally, look at the class differentials as given below:

105

CU IDOL SELF LEARNING MATERIAL (SLM)

Class myabc has three constructors having no parameter, one parameter and two parameters

respectively. When an object to this class is created depending on number of parameters one

of these constructors is selected and is automatically executed.

106

CU IDOL SELF LEARNING MATERIAL (SLM)

5.2.2 Destructor

When a program no longer needs an instantiated object it destroys it. If you do not supply a

destructor function, C++ supplies a default destructor for you, unknown to you. The program

uses the destructor to destroy the object for you. When should you define your own

destructor function? In many cases you do not need a destructor function. However, if your

class created dynamic objects, then you need to define your own destructor in which you

will delete the dynamic objects. This is because dynamic objects cannot be deleted on their

own. So, when the object is destroyed, the dynamic objects are deleted by the destructor

function you define.The destructor will get called again at the close } of the block in which

the local was created. This is a guarantee of the language; it happens automatically; there’s

no way to stop it from happening. But you can get really bad results from calling a

destructor on the same object a second time! Bang! You’re dead!

A destructor function has the same name as the class, and does not have a returned value.

However you must precede the destructor with the tilde sign, which is ~ .

The following code illustrates the use of a destructor against dynamic objects:

107

CU IDOL SELF LEARNING MATERIAL (SLM)

The destructor function is automatically called, without you knowing, when the program no

longer needs the object. If you defined a destructor function as in the above code, it will be

executed. If you did not define a destructor function, C++ supplies you one, which the

program uses unknown to you. However, this default destructor will not destroy dynamic

objects.

108

CU IDOL SELF LEARNING MATERIAL (SLM)

5.3 TYPE OF CONSTRUCTOR

5.3.1Default constructor

If no constructor is defined in the class then the compiler automatically creates one for the

program. This constructor which is created by the compiler when there is no user defined

constructor and which doesn’t take any parameters is called default constructor.

Format of default constructor

/*.....format of default constructor..........*/

class class_name

{

.........

public:

class_name() { }; //default constructor

.........

};

5.5.2 Parameterized Constructor

To put it up simply, the constructor that can take arguments are called parameterized

constructor. In practical programs, we often need to initialize the various data elements of

the different object with different values when they are created. This can be achieved by

passing the arguments to the constructor functions when the object is created.

Following sample program will highlight the concept of parameterized constructor

/*.....A program to find area of rectangle .......... */

109

CU IDOL SELF LEARNING MATERIAL (SLM)

#include<iostream>

using namespace std;

class ABC

{

private:

int length,breadth,x;

public:

ABC (int a,int b) //parameterized constructor to

initialize l and b

{

length = a;

breadth = b;

}

int area( ) //function to find area

{

x = length * breadth;

return x;

}

void display( ) //function to display the area

{

cout << "Area = " << x << endl;

110

CU IDOL SELF LEARNING MATERIAL (SLM)

}

};

int main()

{

ABC c(2,4); //initializing the data members of object 'c'

implicitly

c.area();

c.display();

ABC c1= ABC(4,4); // initializing the data members of

object 'c' explicitly

c1.area();

c1.display();

return 0;

} //end of program

Output

Area = 8

Area = 16

Note: Remember that constructor is always defined and declared in public section of the

class and we can’t refer to their addresses

5.3.3 Copy Constructor

111

CU IDOL SELF LEARNING MATERIAL (SLM)

Generally in a constructor the object of its own class can’t be passed as a value parameter.

But the classes own object can be passed as a reference parameter. Such constructor having

reference to the object of its own class is known as copy constructor.

Moreover, it creates a new object as a copy of an existing object. For the classes which do

not have a copy constructor defined by the user, compiler itself creates a copy constructor

for each class known as default copy constructor.

Example to illustrate the concept of copy constructor

/*.....A program to highlight the concept of copy

constructor.......... */

#include<iostream>

using namespace std;

class example

{

private:

int x;

public:

example (int a) //parameterized constructor to initialize

l and b

{

x = a;

}

example( example &b) //copy constructor with reference

object argument

112

CU IDOL SELF LEARNING MATERIAL (SLM)

{

x = b.x;

}

int display( ) //function to display

{

return x;

}

};

int main()

{

example c1(2); //initializing the data members of

object 'c' implicitly

example c2(c1); //copy constructor called

example c3 = c1;

example c4 = c2;

cout << "example c1 = " << c1.display() << endl;

cout << "example c2 = " << c2.display() << endl;

cout << "example c3 = " << c3.display() << endl;

cout << "example c4 = " << c4.display() << endl;

return 0;

113

CU IDOL SELF LEARNING MATERIAL (SLM)

} //end of program

Output

example c1 = 2

example c2 = 2

example c3 = 2

example c4 = 2

Note: In copy constructor passing an argument by value is not possible.

5.4 DESTRUCTORS

Constructors create an object, allocate memory space to the data members and initialize the

data members to appropriate values; at the time of object creation. Another member method

called destructor does just the opposite when the program creating an object exits, thereby

freeing the memory. A destructive method has the following characteristics:

1. Name of the destructor method is the same as the name of the class preceded by a tilde(~).

2. The destructor method does not take any argument.

3. It does not return any value

The following codes snippet shows the class abc with the destructor method;

114

CU IDOL SELF LEARNING MATERIAL (SLM)

Whenever an object goes out of the scope of the method that created it, its destructor method

is invoked automatically. However if the object was created using new operator, the

destructor must be called explicitly using delete operator. The syntax of delete operator is as

follows:

delete(object);

In reverse order of construction: First constructed, last destructed. In the following example,

the order for destructors will be a[9], a[8], ..., a[1], a[0]:

5.5SUMMARY

A constructor is a member function of a class, having the same name as its

class and which is called automatically each time an object of that class it

created.

115

CU IDOL SELF LEARNING MATERIAL (SLM)

It is used for initializing the member variables with desired initial values. A

variable (including structure and array type) in C++ may be initialized with a

value at the time of its declaration.

The responsibility of initialization may be shifted, however, to the compiler

by including a member function called constructor.

A class constructor, if defined, is called whenever a program created an

object of that class. Constructors are public member unless otherwise there is

a good reason against.

A constructor may take argument (s). A constructor may taking no

argument(s) is known as default constructor.

A constructor may also have parameter (s) or argument (s), which can be

provided at the time of creating an object of that class.

C++ classes are derived data types and so they have constructor (s). Copy

constructor is called whenever an instance of same type is assigned to another

instance of the same class.

If a constructor is called with less number of arguments than required an

error occurs. Every time an object is created its constructor is invoked.

The functions that is automatically called when an object is no more required

is known as destructor. It is also a member function very much like

constructors but with an opposite intent.

We may set the default value for the constructor parameter. A class destructor

is a class method having the same name as the class name and is prefixed

with tilde (~) sign.

The destructor does not return anything and does not accept any argument. A

class definition may contain one and only one destructor.

116

CU IDOL SELF LEARNING MATERIAL (SLM)

5.6 KEY WORDS/ABBREVIATIONS

Constructor: A member function having the same name as its class and that

initializes class objects with legal initial values.

Copy Constructor: A constructor that initializes an object with the data values

of another object.

Default Constructor: A constructor that takes no arguments.

Destructor: A member function having the same name as its class but

preceded by ~ sign and that deinitializes an object before it goes out of scope.

Friend Function: A function which is not a member of a class but which is

given special permission Notes to access private and protected members of

the class.

Static Member Functions: Functions that can access only the static members.

Temporary Object: An anonymous short lived obj

5.7LEARNINGACTIVITY

1.Write C++ program by taking a "patient" class and by using constructor and destructor

__________________________________________________________________________

__________________________________________________________________________

2. Write a program to calculate factorial of a given number using copy constructor.

__________________________________________________________________________

__________________________________________________________________________

5.8 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

117

CU IDOL SELF LEARNING MATERIAL (SLM)

A. Descriptive Types Questions

1. Can one constructor of a class call another constructor of the same class to initialize the

this object? Justify your answers with an example.

2. Should my constructors use “initialization lists” or “assignment”? Discuss.

3. Spot out the error in the following code and correct it.

4. How is a copy constructor different from a constructor? Illustrate with suitable examples

5. Identify and give the specific program for a constructor without parameters

B. Multiple Choice Questions

1. What is the role of a constructor in classes?

(a) To modify the data whenever required

(b) To destroy an object

(c) To initialize the data members of an object when it is created

118

CU IDOL SELF LEARNING MATERIAL (SLM)

(d) To call private functions from the outer world

2. Why constructors are efficient instead of a function init() defined by the user to initialize

the data members of an object?

(a) Because user may forget to call init() using that object leading segmentation fault

(b) Because user may call init() more than once which leads to overwriting values

(c) Because user may forget to define init() function

(d) All of the mentioned

3. What is a copy constructor?

(a) A constructor that allows a user to move data from one object to another

(b) A constructor to initialize an object with the values of another object

(c) A constructor to check the whether to objects are equal or not

(d) A constructor to kill other copies of a given object.

4. What happens if a user forgets to define a constructor inside a class?

(a) Error occurs

(b) Segmentation fault

(c) Objects are not created properly

(d) Compiler provides a default constructor to avoid faults/errors

5. How many parameters does a default constructor require?

(a) 1

(b) 2

(c) 0

(d) 3

Answers

1. (c), 2. (d), 3. (b), 4. (d), 5. (c)

119

CU IDOL SELF LEARNING MATERIAL (SLM)

5.9REFERENCES

Er V. K. Jain, Object Oriented Programming with C++, Cyber Tech Publication,

Daryaganj N Delhi-110002

Bjarne AT&T Labs Murray Hill, New Jersey Stroustrup, Basics of C++

Programming, Special Edition, Publisher: Addison-Wesley Professional.

C/C++ Programming manual – By Tim Lin and Saeed Monemi

http://www.cprogramming.com/tutorial/constructor_destructor_ordering.html

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101 index.jsp?topic=

%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr374.htm

http://www.codezclub.com/cpp-solved-programs-problems-solutions/c-constructor-

destructor-solved-programs-solutions/

Constructing constructors by Kent Reisdorph and Jody Hagins February 1999

C++ Tutorial - Constructor - 2016 Golden Gate Ave, San Francisco

120

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT6 INHERITANCE

Structure

6.0 LearningObjectives

6.1 Introduction

6.2 Defining Derived Class

6.3 Modes of Inheritance

6.3.1 Single Inheritance

6.3.2 Multilevel Inheritance

6.3.3 Multiple Inheritance

6.3.4 Hierarchical Inheritance

121

CU IDOL SELF LEARNING MATERIAL (SLM)

6.3.5 Hybrid Inheritance

6.4 Ambiguity in Multiple and Multipath Inheritance

6.4.1 Ambiguity in Multiple Inheritance

6.4.2 Ambiguity in Multipath Inheritance

6.5 Virtual base class

6.6 Overriding Member Function

6.7 Member Classes: Nesting of Classes

6.8 Summary

6.9 KeyWords/Abbreviations

6.10 LearningActivity

6.11 Unit End Questions (MCQ andDescriptive)

6.12 References

6.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize the inheritance

Describe the different types of inheritance

Explain the ambiguity in multiple and multipath inheritance

Discuss the virtual base class

Identify the overriding member function.

6.1 INTRODUCTION

122

CU IDOL SELF LEARNING MATERIAL (SLM)

Reusability of code is a characteristic feature of OOP. C++ strongly supports the concept of

reusability. The C++ classes can be used again in several ways. Once a class has been

written andtested, it can be adopted by other programmers. New classes can be defined

reusing the properties Notes of existing ones. The mechanism of deriving a new class from

an old one is called ‘INHERITANCE’. This is often referred to as ‘IS-A’ relationship

because every object of the class being defined “is” also an object of inherited class type.

The old class is called ‘BASE’ class and the new one is called ‘DERIVED’ class or sub-

class.

6.2DEFINING DERIVED CLASS

A derived class is specified by defining its relationship with the base class in addition to its

own details. The general syntax of defining a derived class is as follows:

The colon (:) indicates that the derivedclassname class is derived from the baseclassname

class. The access_specifier or the visibility mode is optional and, if present, may be public,

private or protected. By default it is private. Visibility mode describes the accessibility status

of derived features. For example,

123

CU IDOL SELF LEARNING MATERIAL (SLM)

In inheritance, some of the base class data elements and member functions are inherited into

the derived class and some are not. We can add our own data and member functions and thus

extend the functionality of the base class.

6.3 FORMS OF INHERITANCE

6.3.1 Single Inheritance

When a class inherits from a single base class, it is referred to as single inheritance.

Following program shows single inheritance using public derivation

124

CU IDOL SELF LEARNING MATERIAL (SLM)

6.3.2 Multiple Inheritance

A class can inherit the attributes of two or more classes. This mechanism is known as

‘MULTIPLE INHERITANCE’. Multiple inheritance allows us to combine the features of

several existing classes as a starting point for defining new classes. The syntax of the

derived class is as follows:

125

CU IDOL SELF LEARNING MATERIAL (SLM)

6.1 Multiple Inheritance

Where the visibility refers to the access specifiers i.e. public, private or protected. Following

program shows the multiple inheritance.

We present the below program to demonstrate Multiple Inheritance.

#include <iostream>

usingnamespacestd;

//multiple inheritance example

classstudent_marks {

protected:

introllNo, marks1, marks2;

public:

voidget() {

cout << "Enter the Roll No.: "; cin >> rollNo;

126

CU IDOL SELF LEARNING MATERIAL (SLM)

cout << "Enter the two highest marks: "; cin >>

marks1 >> marks2;

}

};

classcocurricular_marks {

protected:

intcomarks;

public:

voidgetsm() {

cout << "Enter the mark for CoCurricular

Activities: "; cin >> comarks;

}

};

//Result is a combination of subject_marks and

cocurricular activities marks

classResult : publicstudent_marks,

publiccocurricular_marks {

inttotal_marks, avg_marks;

public:

voiddisplay()

{

127

CU IDOL SELF LEARNING MATERIAL (SLM)

total_marks = (marks1 + marks2 + comarks);

avg_marks = total_marks / 3;

cout << "\nRoll No: "<< rollNo << "\nTotal

marks: "<< total_marks;

cout << "\nAverage marks: "<< avg_marks;

}

};

intmain()

{

Result res;

res.get(); //read subject marks

res.getsm(); //read cocurricular activities marks

res.display(); //display the total marks and

average marks

}

Output:

Enter the Roll No.: 25

Enter the two highest marks: 40 50

Enter the mark for CoCurricular Activities: 30

Roll No: 25

Total marks: 120

Average marks: 40

128

CU IDOL SELF LEARNING MATERIAL (SLM)

6.3.3 Multilevel Inheritance

Multiple Inheritance is pictorially represented below. When the inheritance is such that, the

class A serves as a base class for a derived class B which in turn serves as a base class for

the derived class C. This type of inheritance is called ‘MULTILEVEL INHERITANCE’.

The class B is known as the ‘INTERMEDIATE BASE CLASS’ since it provides a link for

the inheritance between A and C. The chain ABC is called ‘INHERITANCE*PATH’ for

e.g.

Fig 6.2 Multilevel Inheritance

Let us see an example of Multilevel Inheritance.

#include <iostream>

#include <string>

usingnamespacestd;

classAnimal

129

CU IDOL SELF LEARNING MATERIAL (SLM)

{

string name="";

public:

inttail=1;

intlegs=4;

};

classDog : publicAnimal

{

public:

voidvoiceAction()

{

cout<<"Barks!!!";

}

};

classPuppy:publicDog{

public:

voidweeping()

{

130

CU IDOL SELF LEARNING MATERIAL (SLM)

cout<<"Weeps!!";

}

};

intmain()

{

Puppy puppy;

cout<<"Puppy has "<<puppy.legs<<" legs"<<endl;

cout<<"Puppy has "<<puppy.tail<<" tail"<<endl;

cout<<"Puppy ";

puppy.voiceAction();

cout<<" Puppy ";

puppy.weeping();

}

Output:

Puppy has 4 legs

Puppy has 1 tail

Puppy Barks!!! Puppy Weeps!!

Here we modified the example for Single inheritance such that there is a new class Puppy

which inherits from the class Dog that in turn inherits from class Animal. We see that the

class Puppy acquires and uses the properties and methods of both the classes above it.

6.3.4 Hierarchical Inheritance

131

CU IDOL SELF LEARNING MATERIAL (SLM)

Another interesting application of inheritance is to use is as a support to a hierarchical design

of a class program. Many programming problems can be cast into a hierarchy where certain

features of one level are shared by many others below that level for e.g.

Fig 6.3 HierarchicalInheritance

Example demonstrating Hierarchical Inheritance

#include <iostream>

usingnamespacestd;

//hierarchical inheritance example

classShape // shape class -> base class

{

public:

intx,y;

voidget_data(intn,intm) {

132

CU IDOL SELF LEARNING MATERIAL (SLM)

x= n;

y = m;

}

};

classRectangle : publicShape // inherit Shape

class

{

public:

intarea_rect() {

intarea = x*y;

returnarea;

}

};

classTriangle : publicShape // inherit Shape class

{

public:

inttriangle_area() {

floatarea = 0.5*x*y;

returnarea;

}

133

CU IDOL SELF LEARNING MATERIAL (SLM)

};

classSquare : publicShape // inherit Shape class

{

public:

intsquare_area() {

floatarea = 4*x;

returnarea;

}

};

intmain()

{ Rectangle r;

Triangle t;

Square s;

intlength,breadth,base,height,side;

//area of a Rectangle

std::cout << "Enter the length and breadth of a

rectangle: "; cin>>length>>breadth;

r.get_data(length,breadth);

intrect_area = r.area_rect();

std::cout << "Area of the rectangle =

134

CU IDOL SELF LEARNING MATERIAL (SLM)

"<<rect_area<< std::endl;

//area of a triangle

std::cout << "Enter the base and height of the

triangle: "; cin>>base>>height;

t.get_data(base,height);

floattri_area = t.triangle_area();

std::cout <<"Area of the triangle = "<<

tri_area<<std::endl;

//area of a Square

std::cout << "Enter the length of one side of the

square: "; cin>>side;

s.get_data(side,side);

intsq_area = s.square_area();

std::cout <<"Area of the square = "<<

sq_area<<std::endl;

return0;

}

Output:

Enter the length and breadth of a rectangle: 10 5

Area of the rectangle = 50

Enter the base and height of the triangle: 4 8

Area of the triangle = 16

135

CU IDOL SELF LEARNING MATERIAL (SLM)

Enter the length of one side of the square: 5

Area of the square = 20

The above example is a classic example of class Shape. We have a base class Shape and

three classes i.e. rectangle, triangle, and square are derived from it. We have a method to

read data in the Shape class while each derived class has its own method to calculate area. In

the main function, we read data for each object and then calculate the area.

6.3.5 Hybrid Inheritance

There could be situations where we need to apply two or more types of inheritance to design

a program. Basically Hybrid Inheritance is the combination of one or more types of the

inheritance. Here is one implementation of hybrid inheritance.

#include <iostream>

#include <string>

usingnamespacestd;

//Hybrid inheritance = multilevel + multilpe

classstudent{ //First base Class

intid;

string name;

public:

voidgetstudent(){

cout << "Enter student Id and student

name"; cin >> id >> name;

136

CU IDOL SELF LEARNING MATERIAL (SLM)

}

};

classmarks: publicstudent{ //derived from student

protected:

intmarks_math,marks_phy,marks_chem;

public:

voidgetmarks(){

cout << "Enter 3 subject marks:"; cin

>>marks_math>>marks_phy>>marks_chem;

}

};

classsports{

protected:

intspmarks;

public:

voidgetsports(){

cout << "Enter sports marks:"; cin >>

spmarks;

}

};

137

CU IDOL SELF LEARNING MATERIAL (SLM)

classresult : publicmarks, publicsports{//Derived class

by multiple inheritance//

inttotal_marks;

floatavg_marks;

public:

voiddisplay(){

total_marks=marks_math+marks_phy+marks_chem;

avg_marks=total_marks/3.0;

cout << "Total marks ="<< total_marks <<

endl;

cout << "Average marks ="<< avg_marks <<

endl;

cout << "Average + Sports marks ="<<

avg_marks+spmarks;

}

};

intmain(){

result res;//object//

res.getstudent();

res.getmarks();

138

CU IDOL SELF LEARNING MATERIAL (SLM)

res.getsports();

res.display();

return0;

}

Output:

Enter student Id and student name 25 Ved

Enter 3 subject marks:89 88 87

Enter sports marks:40

Total marks =264

Average marks =88

Average + Sports marks =128

Here we have four classes i.e. Student, Marks, Sports, and Result. Marks are derived from

the student class. The class Result derives from Marks and Sports as we calculate the result

from the subject marks as well as sports marks. The output is generated by creating an object

of class Result that has acquired the properties of all the three classes. Note that in hybrid

inheritance as well, the implementation may result in “Diamond Problem” which can be

resolved using “virtual” keyword as mentioned previously.

6.4AMBIGUITY IN MULTIPLE AND MULTIPATH INHERITANCE

6.4.1 Ambiguity in Multiple Inheritance

In multiple inheritances, there may be possibility that a class may inherit member functions

with same name from two or more base classes and the derived class may not have functions

with same name as those of its base classes. If the object of the derived class need to access

one of the same named member function of the base classes then it result in ambiguity as it

is not clear to the compiler which base’s class member function should be invoked. The

139

CU IDOL SELF LEARNING MATERIAL (SLM)

ambiguity simply means the state when the compiler confused.

Syntax:

class a

{

private:

…………….

public:

void abc () {}

…………….

…………….

};

class b

{

private:

…………….

public:

void abc() {}

…………….

…………….

};

140

CU IDOL SELF LEARNING MATERIAL (SLM)

class c : public a , public b

{

private:

…………….

public:

…………….

…………….

};

void main()

{

c obj;

obj.abc();//Error

……………..

}

In this example, the two base classes a and b have function of same name abc() which are

inherited to the derived class c. When the object of the class c is created and call the function

abc() then the compiler is confused which base’s class function is called by the compilerThe

ambiguity can be resolved by using the scope resolution operator to specify the class in

which the member function lies as given below:

obj.a :: abc();

This statement invoke the function name abc() which are lies in base class a.

6.4.2 Ambiguity in Multipath Inheritance

141

CU IDOL SELF LEARNING MATERIAL (SLM)

Sometimes we need to apply two or more types of inheritance to design a program and this

type of inheritance are called hybrid inheritance. But in hybrid inheritance, if multiple paths

exit between a base class and derived class through different intermediate classes, then

derived class inherits the members of the base class more than one time and it results in

ambiguity. Here, base class is called indirect base class and intermediate base classes are

called direct base classes. To avoid this ambiguity, the indirect base class is made virtual

base class and to define base class as virtual, a keyword virtual is appended when extending

the direct base classes from the indirect base class as given in the example. In this way,

when we define the indirect base class virtual, compiler take care that only one copy of that

class is inherited, regardless of how many inherited paths exist between the virtual base class

and the derived class.

Fig 6.4 Hybrid inheritance

#include <iostream>

#include <conio>

using namespace std;

class person

{

public:

142

CU IDOL SELF LEARNING MATERIAL (SLM)

char name[100];

int code;

void input()

{

cout<<"\nEnter the name of the person : ";

cin>>name;

cout<<endl<<"Enter the code of the person : ";

cin>>code;

}

void display()

{

cout<<endl<<"Name of the person : "<<name;

cout<<endl<<"Code of the person : "<<code;

}

};

class account:virtual public person

{

public:

float pay;

void getpay()

143

CU IDOL SELF LEARNING MATERIAL (SLM)

{

cout<<endl<<"Enter the pay : ";

cin>>pay;

}

void display()

{

cout<<endl<<"Pay : "<<pay;

}

};

class admin:virtual public person

{

public:

int experience;

void getexp()

{

cout<<endl<<"Enter the experience : ";

cin>>experience

}

void display()

144

CU IDOL SELF LEARNING MATERIAL (SLM)

{

cout<<endl<<"Experience : "<<experience;

}

};

class master:public account,public admin

{

public:

char n[100];

void gettotal()

{

cout<<endl<<"Enter the company name : ";

cin>>n;

}

void display()

{

cout<<endl<<"Company name : "<<n;

}

};

int main()

{

145

CU IDOL SELF LEARNING MATERIAL (SLM)

master m1;

m1.input();

m1.getpay();

m1.getexp();

m1.gettotal();

m1.person::display();

m1.account::display();

m1.admin::display();

m1.display();

return 0;

Output:

Enter the name of the person : Chetali

Enter the code of the person : 1224

Enter the pay : 20000

Enter the experience : 2

Enter the company name : Hitech

Name of the person : Chetali

Code of the person : 1224

Pay : 20000

146

CU IDOL SELF LEARNING MATERIAL (SLM)

Experience : 2

Company name : Hitech

6.5 VIRTUAL BASE CLASS

We have just discussed a situation which would require the use of both multiple and multi

level inheritance. Consider a situation, where all the three kinds of inheritance, namely

multi-level, multiple and hierarchical are involved. Let us say the ‘child’ has two direct base

classes ‘parent1’ and ‘parent2’ which themselves has a common base class ‘grandparent’.

The child inherits the traits of ‘grandparent’ via two separate paths. It can also be inherit

directly as shown by the broken line. The grandparent is sometimes referred to as

‘INDIRECT BASE CLASS’. Now, the Inheritance by the child might cause some problems.

All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first

via ‘parent1’ and again via ‘parent2’. So, there occurs a duplicacy which should be avoided.

The duplication of the inherited members can be avoided by making common base class as

the virtual base class: for e.g.

147

CU IDOL SELF LEARNING MATERIAL (SLM)

Program to show the virtual base class

#include<iostream.h>

#include<conio.h>

class ClassA

{

public:

int a;

};

class ClassB : virtual public ClassA

{

148

CU IDOL SELF LEARNING MATERIAL (SLM)

public:

int b;

};

class ClassC : virtual public ClassA

{

public:

int c;

};

class ClassD : public ClassB, public ClassC

{

public:

int d;

};

void main()

{

ClassD obj;

obj.a = 10; //Statement 1

obj.a = 100; //Statement 2

obj.b = 20;

obj.c = 30;

149

CU IDOL SELF LEARNING MATERIAL (SLM)

obj.d = 40;

cout<< "\n A : "<< obj.a;

cout<< "\n B : "<< obj.b;

cout<< "\n C : "<< obj.c;

cout<< "\n D : "<< obj.d;

}

Output :

A : 100

B : 20

C : 30

D : 40

According to the above example, ClassD have only one copy of ClassA and statement 4 will

overwrite the value of a, given in statement 3.

6.6 OVERRIDING MEMBER FUNCTION

If there are two functions with the same name in the base class and derived class and even

the address of derived class is assigned to the pointer of base class; it executes the function

of base class. But by declaring the base class function as virtual, pointer to base class

executes the function of derived class. And in this way base class pointer behaves differently

at different situation and applies the concept of polymorphism. This is also called run time

or dynamic polymorphism because when a function made virtual, C++ determines which

function to use at run time based on the type of object pointed to by the base pointer, rather

than the type of the pointer.

150

CU IDOL SELF LEARNING MATERIAL (SLM)

Function Overriding Example

To override a function you must have the same signature in child class. By signature I mean

the data type and sequence of parameters. Here we don’t have any parameter in the parent

function so we didn’t use any parameter in the child function.

#include<iostream>

usingnamespace std;

classBaseClass{

public:

void disp(){

cout<<"Function of Parent Class";

}

};

classDerivedClass:publicBaseClass{

public:

void disp(){

cout<<"Function of Child Class";

}

};

int main(){

DerivedClass obj =DerivedClass();

obj.disp();

151

CU IDOL SELF LEARNING MATERIAL (SLM)

return0;

}

Output:

Function of ChildClass

Note: In function overriding, the function in parent class is called the overridden function

and function in child class is called overriding function.

6.7 MEMBER CLASSES: NESTING OF CLASSES.

A nested class is a class that is declared in another class. The nested class is also a member

variable of the enclosing class and has the same access rights as the other members.

However, the member functions of the enclosing class have no special access to the

members of a nested class.

A program that demonstrates nested classes in C++ is as follows.

Example

#include<iostream>

usingnamespace std;

class A {

public:

class B {

private:

int num;

public:

152

CU IDOL SELF LEARNING MATERIAL (SLM)

void getdata(int n){

num = n;

}

void putdata(){

cout<<"The number is "<<num;

}

};

};

int main(){

cout<<"Nested classes in C++"<< endl;

A :: B obj;

obj.getdata(9);

obj.putdata();

return0;

}

Output

Nested classes in C++

The number is 9

In the above program, class B is defined inside the class A so it is a nested class. The class B

contains a private variable num and two public functions getdata() and putdata(). The

function getdata() takes the data and the function putdata() displays the data. This is given as

153

CU IDOL SELF LEARNING MATERIAL (SLM)

follows.

class A {

public:

class B {

private:

int num;

public:

void getdata(int n){

num = n;

}

void putdata(){

cout<<"The number is "<<num;

}

};

};

In the function main(), an object of the class A and class B

is defined. Then the functions getdata() and putdata() are

called using the variable obj. This is shown below.

cout<<"Nested classes in C++"<< endl;

A :: B obj;

obj.getdata(9);

154

CU IDOL SELF LEARNING MATERIAL (SLM)

obj.putdata();

6.8SUMMARY

Inheritance is the capability of one class to inherit properties from another

class.

It supports reusability of code and is able to simulate the transitive nature of

real life objects. Inheritance has many forms: Single inheritance, multiple

inheritance, hierarchical inheritance, multilevel inheritance and hybrid

inheritance.

A subclass can derive itself publicly, privately or protectedly. The derived

class constructor is responsible for invoking the base class constructor, the

derived class can directly access only the public and protected members of

the base class.

When a class inherits from more than one base class, this is called multiple

inheritance.

A class may contain objects of another class inside it. his situation is called

nesting of objects and in such a situation, the contained objects are

constructed first before constructing the objects of the enclosing class.

Single Inheritance: Where a class inherits from a single base class, it is

known as single inheritance.

Multilevel Inheritance: When the inheritance is such that the class. A serves

as a base class for a derived class B which is turn serves as a base class for

the derived class C. This type of inheritance is called ‘Multilevel Inheritance.

Both inheritance and composition allow you to create a new type from

existing types, and both embed sub objects of the existing types inside the

155

CU IDOL SELF LEARNING MATERIAL (SLM)

new type. Typically, however, you use composition to reuse existing types as

part of the underlying implementation of the new type and inheritance when

you want to force the new type to be the same type as the base class (type

equivalence guarantees interface equivalence).

Multiple Inheritance: A class inherit the attributes of two or more classes.

This mechanism is known as Multiple Inheritance.’

Hybrid Inheritance: The combination of one or more types of the inheritance.

Overriding helps in: Redefining inherited methods in subclasses. In

redefinition declaration should be identical, code may be different. It is like

having another version of the same product.

6.9KEY WORDS/ABBREVIATIONS

Abstract Class: A class serving only a base class for other classes and no objects

of which are created.

Base class: A class from which another class inherits. (Also called super class)

Containership: The relationship of two classes such that the objects of a class

are enclosed within the other class.

Derived class: A class inheriting properties from another class. (also called sub

class) Inheritance: Capability of one class to inherit properties from another class.

Inheritance Graph: The chain depicting relationship between a base class and

derived class. Visibility Mode: The public, private or protected specifier that

controls the visibility and availability of a member in a class.

156

CU IDOL SELF LEARNING MATERIAL (SLM)

6.10LEARNINGACTIVITY

1. Write program on Example of Multiple Inheritances: Bank

__________________________________________________________________________

__________________________________________________________________________

2. We want to calculate the total marks of each student of a class in Physics, Chemistry and

Mathematics and the average marks of the class. The number of students in the class is

entered by the user. Create a class named Marks with data members for roll number, name

and marks. Create three other classes inheriting the Marks class, namely Physics, Chemistry

and Mathematics, which are used to define marks in individual subject of each student. Roll

number of each student will be generated automatically. Write program for it.

__________________________________________________________________________

__________________________________________________________________________

6.11 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. Consider a situation where three kinds of inheritance are involved. Explain this

157

CU IDOL SELF LEARNING MATERIAL (SLM)

situation with an example.

2. What is the difference between protected and private members?

3. Scrutinize the major use of multilevel inheritance.

4. Discuss a situation in which the private derivation will be more appropriate as

compared to public derivation.

5. Identify program for the classes Car and Paccar are to modify to allow objects to be

created and destroyed. In addition, the class Truck is to be added to the class hierarchy.

B. Multiple Choice Questions

1. Which among the following best describes the Inheritance?

(a) Copying the code already written

(b) Using the code already written once

(c) Using already defined functions in programming language

(d) Using the data and functions into derived segment

2. How many basic types of inheritance are provided as OOP feature?

(a) 4

(b) 3

(c) 2

(d) 1

3. Which among the following best defines single level inheritance?

(a) A class inheriting a derived class

(b) A class inheriting a base class

(c) A class inheriting a nested class

(d) A class which gets inherited by 2 classes

4. Which among the following is correct for multiple inheritance?

(a) class student{public: int marks;}s; class stream{int total;}; class topper: public

student, public stream{ };

158

CU IDOL SELF LEARNING MATERIAL (SLM)

(b) class student{int marks;}; class stream{ }; class topper: public student{ };

(c) class student{int marks;}; class stream:public student{ };

(d) class student{ }; class stream{ }; class topper{ };

5. Which programming language doesn’t support multiple inheritance?

(a) C++ and Java

(b) C and C++

(c) Java and SmallTalk

(d) Java

Answers

1. (d), 2. (a), 3. (b), 4. (a), 5. (d)

6.12REFERENCES

Nell B. Dale, Study guide for C++ Plus Data Structure, Academic Internet Publishers

Yashavant Kanetkar, C++ Programming, 1st Edition, BPB Publication.

Kyle Loudon, C++ Pocket Reference 1st Edition, O’reilly Publication

http://msdn.microsoft.com/en-us/library/wcz57btd(v=vs.80).aspx

http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/

https://www.w3schools.com/java/java_inheritance.asp.

Inheritance and Its Type in Object Oriented Programming Using C++ 18 Sep 2019Dr

Mehul Patel

Uses and Abuses of Inheritance, Part 1 ++ Report, 10(9), October 1998.

159

CU IDOL SELF LEARNING MATERIAL (SLM)

160

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 7 POLYMORPHISM

Structure

7.0 LearningObjectives

7.1 Introduction

7.2 Introduction &Types of polymorphism

7.2.1 Compile time Polymorphism

7.2.2 Runtime Polymorphism

7.3 Function overloading

7.4 Operator overloading

7.5 Rules for overloading operators

7.6 Overloading of unary operators

7.7 Overloading of binaryoperators

7.7.1 Using friend function

7.7.2 Using member function

7.8 Summary

7.9 KeyWords/Abbreviations

7.10 LearningActivity

7.11 Unit End Questions (MCQ andDescriptive)

7.12 References

161

CU IDOL SELF LEARNING MATERIAL (SLM)

7.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Explain the polymorphismand its type

Discuss Function overloading

Discuss operator overloading

Explain Overloading of unary & binary operators

7.1 INTRODUCTION

The word polymorphism means having many forms. Typically, polymorphism occurs when

there is a hierarchy of classes and they are related by inheritance .C++ polymorphism means

that a call to a member function will cause a different function to be executed depending on

the type of object that invokes the function.By default, C++ matches a function call with the

correct function definition at compile time. This is called static binding. You can specify that

the compiler match a function call with the correct function definition at run time; this is

called dynamic binding. You declare a function with the keyword virtual if you want the

compiler to use dynamic binding for that specific function.Conceptually an object may have

only data members specifying its attributes. However, such an object would serve no useful

purpose. For the purpose of establishing communication with the object it is necessary that

the object provide methods, which are C like functions. Though C++ functions are very

similar to C functions, yet they differ significantly as you will discover in this unit.C++

provides a rich collection of operators. You have already seen the meaning and uses of many

such operators in previous units. One special feature offered by C++ is operator overloading.

This feature is necessary in a programming language supporting objects oriented features

162

CU IDOL SELF LEARNING MATERIAL (SLM)

7.2 INTRODUCTION & TYPES OF POLYMORPHISM

Polymorphism plays an important role in allowing objects having different internal

structures to share the same external interface. This means that a general class of operations

may beaccessed in the same manner even though specific actions associated with each

operation may differ. Polymorphism is extensively used in implementing inheritance as

shown below.

Fig 7.1 Polymorphism implement in inheritance

Polymorphism can be implemented using operator and function overloading, where the same

operator and function works differently on different arguments producing different results.

These polymorphisms are brought into effect at compile time itself, hence is known as early

binding, static binding, static linking or compile time polymorphism. However, ambiguity

creeps in when the base class and the derived class both have a function with same name.

For instance, let us consider the following code snippet.

163

CU IDOL SELF LEARNING MATERIAL (SLM)

Since, both the functions aa. display () and bb. display () is same but at in different classes,

there is no overloading, and hence early binding does not apply. The appropriate function is

chosen at the run time – run time polymorphism. C++ supports run-time polymorphism by a

mechanism called virtual function. It exhibits late binding or dynamic linking. As stated

earlier, polymorphism refers to the property by which objects belonging to different classes

are able to respond to the same message, but in different forms. Therefore, an essential

feature of polymorphism is the ability to refer to objects without any regard to their classes.

It implies that a single pointer variable may refer to object of different classes. However, a

base pointer, even if is made to contain the address of the derived class, always executes the

function in the base class. The compiler ignores the content of the pointer andchooses the

member function that matches the type of the pointer. Thus, the polymorphism Notes stated

above cannot be implemented by this mechanism.

164

CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 7.2 Polymorphism in C++

The biggest advantage of polymorphism is creation of reusable code by programmer‟s

classes once written, tested and implemented can be easily reused without caring about

what’s written in the case.

Polymorphic variables help with memory use, in that a single variable can be used to store

multiple data types (integers, strings, etc.) rather than declaring a different variable for each

data format to be used. Polymorphism is a powerful feature of the object oriented

programming language C++.

Applications are Easily Extendable: Once an application is written using the concept of

polymorphism, it can easily be extended, providing new objects that conform to the original

interface. It is unnecessary to recompile original programs by adding new types. Only re-

linking is necessary to exhibit the new changes along with the old application. This is the

greatest achievement of C++ object-oriented programming. In programming language, there

has always been a need for adding and customizing. By utilizing the concept of

polymorphism, time and work effort is reduced in addition to making future maintenance

easier.

It provides easier maintenance of applications.

It helps in achieving robustness in applications.

165

CU IDOL SELF LEARNING MATERIAL (SLM)

Types of Polymorphism

Polymorphism is a feature of OOPs that allows the object to behave differently in different

conditions.

In C++ we have two types of polymorphism:

1) Compile time Polymorphism – This is also known as static (or early) binding.

2) Runtime Polymorphism – This is also known as dynamic (or late) binding.

7.2.1 Compile time Polymorphism

Function overloading and Operator overloading are perfect example of Compile time

polymorphism. Compile time Polymorphism Example In this example, we have two

functions with same name but different number of arguments. Based on how many

parameters we pass during function call determines which function is to be called, this is

why it is considered as an example of polymorphism because in different conditions the

output is different. Since, the call is determined during compile time that’s why it is called

compile time polymorphism.

#include<iostream>

usingnamespace std;

classAdd{

public:

int sum (int num1,int num2) {

return num1+num2;

}

int sum (int num1,int num2,int num3) {

166

CU IDOL SELF LEARNING MATERIAL (SLM)

return num1+num2+num3;

}

};

int main(){

Add obj;

//This will call the first function

cout<<"Output: "<<obj.sum(10,20)<<endl;

//This will call the second function

cout<<"Output: "<<obj.sum(11,22,33);

return0;

}

Output:

Output:30

Output:66

7.2.2 Runtime Polymorphism

Function overriding is an example of Runtime polymorphism. In case of function overriding

we have two definitions of the same function, one is parent class and one in child class. The

call to the function is determined at runtime to decide which definition of the function is to

be called, that’s the reason it is called runtime polymorphism.

Example of Runtime Polymorphism

#include<iostream>

167

CU IDOL SELF LEARNING MATERIAL (SLM)

usingnamespace std;

class A {

public:

void disp(){

cout<<"Super Class Function"<<endl;

}

};

class B:public A{

public:

void disp(){

cout<<"Sub Class Function";

}

};

int main(){

//Parent class object

A obj;

obj.disp();

//Child class object

B obj2;

obj2.disp();

168

CU IDOL SELF LEARNING MATERIAL (SLM)

return0;

}

Output:

SuperClassFunction

SubClassFunction

7.3 FUNCTION OVERLOADING

A function may take zero or more arguments when called. The number and type of

arguments that a function may take is defined in the function itself. If a function call fails to

comply by the number and type of argument(s), the compiler reports the same as error.

Suppose we write a function named sum to add two numerical values given as arguments.

One can write the function as:

Now suppose we want the function to take float type argument then the function definition

must be changed as:

169

CU IDOL SELF LEARNING MATERIAL (SLM)

This can be very tiring and extremely difficult to remember all the names. Function

overloading is a mechanism that allows a single function name to be used for different

functions. The compiler does the rest of the job. It matches the argument numbers and types

to determine which functions are being called. Thus we may rewrite the above listed

functions using function overloading as:

170

CU IDOL SELF LEARNING MATERIAL (SLM)

Overloaded functions have the same name but different number and type of arguments. They

can differ either by number of arguments or type of arguments or both. However, two

overloaded function cannot differ only by the return type.

7.4 OPERATOR OVERLOADING

Overloading an operator simply means attaching additional meaning and semantics to an

operator. It enables an operator to exhibit more than one operation polymorphically, as

illustrated below: You know that addition operator (+) is essentially a numeric operator and

therefore, requires two number operands. It evaluates to a numeric value, which is equal to

171

CU IDOL SELF LEARNING MATERIAL (SLM)

the sum of the two operands. Evidently this cannot be used in adding two strings. However,

we can extend the operation of addition operator to include string concatenation.

Consequently, the addition operator would work as follows: “COM” + “PUTER.should

produce a single string “COMPUTER” This act of redefining the effect of an operator is

called operator overloading. The original meaning and action of the operator however

remains as it is. Only an additional meaning is added to it. Function overloading allows

different functions with different argument list having the same name. Similarly an operator

can be redefined to perform additional tasks. Operator overloading is accomplished using a

special function, which can be a member function or friend function. The general syntax of

operator overloading is:

Here, operator is the keyword and is preceded by the return_type of the operation. To

overload the addition operator (+) to concatenate two characters, the following declaration,

which could be either member or friend function, would be needed:

A simple and complete example

#include<iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i =0) {real = r; imag =

i;}

172

CU IDOL SELF LEARNING MATERIAL (SLM)

// This is automatically called when '+' is used

with

// between two Complex objects

Complex operator + (Complex const &obj) {

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

}

void print() { cout << real << " + i" << imag <<

endl; }

};

int main()

{

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2; // An example call to

"operator+"

c3.print();

}

Output:

173

CU IDOL SELF LEARNING MATERIAL (SLM)

12 + i9

7.5 RULES FOR OVERLOADING OPERATORS

To overload any operator, we need to understand the rules applicable Let us revise some of

them which have already been explored. Following are the operators that cannot be

overloaded.

Table 7.1 Operators that cannot be Overloaded

1. Operators already predefined in the C++ compiler can be only overloaded. Operator

cannot change operator templates that is for example the increment operator ++ is used only

as unary operator. It cannot be used as binary operator.

2. Overloading an operator does not change its basic meaning. For example assume the +

operator can be overloaded to subtract two objects. But the code becomes unreachable

174

CU IDOL SELF LEARNING MATERIAL (SLM)

3. Unary operators, overloaded by means of a member function, take no explicit argument

and return no explicit values. But, those overloaded by means of a friend function take one

reference argument (the object of the relevant class).

4. Binary operators overloaded through a member function take one explicit argument and

those which are overloaded through a friend function take two explicit arguments

Table 7.2 Operator overloading rules

5. Overloaded operators must either be a non-static class member function or a global

function. A global function that needs access to private or protected class members must be

declared as a friend of that class. A global function must take at least one argument that is of

class or enumerated type or that is a reference to a class or enumerated type.

Example:

175

CU IDOL SELF LEARNING MATERIAL (SLM)

7.6 OVERLOADING UNARY OPERATORS

In case of unary operator overloaded using a member function no argument is passed to the

function whereas in case of a friend function a single argument must be passed. Following

program overloads the unary operator to negate an object. The operator function defined

outside the class negates the individual data members of the class integer.

// C++ program to show unary operator overloading

#include <iostream>

using namespace std;

class Distance {

public:

// Member Object

int feet, inch;

// Constructor to initialize the object's value

176

CU IDOL SELF LEARNING MATERIAL (SLM)

Distance(int f, int i)

{

this->feet = f;

this->inch = i;

}

// Overloading(-) operator to perform decrement

// operation of Distance object

void operator-()

{

feet--;

inch--;

cout << "\nFeet & Inches(Decrement): " << feet << "'" << inch;

}

};

// Driver Code

int main()

{

// Declare and Initialize the constructor

177

CU IDOL SELF LEARNING MATERIAL (SLM)

Distance d1(8, 9);

// Use (-) unary operator by single operand

-d1;

return 0;

}

Output:

Feet & Inches(Decrement): 7'8

In the above program, it shows that no argument is passed and no return_type value is

returned, because unary operator works on a single operand. (-) operator change the

functionality to its member function.

Note: d2 = -d1 will not work, because operator-() does not return any value.

7.7 OVERLOADING BINARY OPERATORS

Binary Operators are operators, which require two operands to perform the operation. When

they are overloaded by means of member function, the function takes one argument, whereas

it takes two arguments in case of friend function. This will be better understood by means of

the following program.

// C++ program to show binary operator

overloading

#include <iostream>

using namespace std;

class Distance {

178

CU IDOL SELF LEARNING MATERIAL (SLM)

public:

// Member Object

int feet, inch;

// No Parameter Constructor

Distance()

{

this->feet = 0;

this->inch = 0;

}

// Constructor to initialize the object's

value

// Parametrized Constructor

Distance(int f, int i)

{

this->feet = f;

this->inch = i;

}

// Overloading (+) operator to perform

addition of

// two distance object

179

CU IDOL SELF LEARNING MATERIAL (SLM)

Distance operator+(Distance& d2) // Call by

reference

{

// Create an object to return

Distance d3;

// Perform addition of feet and inches

d3.feet = this->feet + d2.feet;

d3.inch = this->inch + d2.inch;

// Return the resulting object

return d3;

}

};

// Driver Code

int main()

{

// Declaring and Initializing first object

Distance d1(8, 9);

// Declaring and Initializing second object

Distance d2(10, 2);

// Declaring third object

180

CU IDOL SELF LEARNING MATERIAL (SLM)

Distance d3;

// Use overloaded operator

d3 = d1 + d2;

// Display the result

cout << "\nTotal Feet & Inches: " << d3.feet

<< "'" << d3.inch;

return 0;

}

Output:

Total Feet & Inches: 18'11

7.7.1 Using Friend Function

The following program is the same as previous one. The only difference is that we use a

friend function to find the sum of two objects. Note that an argument is passed to this friend

function

181

CU IDOL SELF LEARNING MATERIAL (SLM)

182

CU IDOL SELF LEARNING MATERIAL (SLM)

You should see the following output.

value = 11

value = 22

value = 33

Friend function being a non-member function does not belong to any class. This function is

invoked like a normal function. Hence the two objects that are to be added have to be passed

as arguments exclusively.

7.7.2 Using Member Function

In the unit on overloading the arithmetic operators, you learned that when the operator does

not modify its operands, it’s best to implement the overloaded operator as a friend function

183

CU IDOL SELF LEARNING MATERIAL (SLM)

of the class. For operators that do modify their operands, we typically overload the operator

using a member function of the class. Overloading operators using a member function is

very similar to overloading operators using a friend function. When overloading an operator

using a member function:

1. The leftmost operand of the overloaded operator must be an object of the class type.

2. The leftmost operand becomes the implicit *this parameter. All other operands become

function parameters. Most operators can actually be overloaded either way, however there

are a few exception cases:

3. If the leftmost operand is not a member of the class type, such as when overloading

operator+ (int, YourClass), or operator<<(ostream&, YourClass), the operator must be

overloaded as a friend.

4. The assignment (=), subscript ([]), call (()), and member selection (->) operators must be

overloaded as member functions.

Overloading the unary negative (–) operator the negative operator is a unary operator that

can be implemented using either method. Before we show you how to overload the operator

using a member function, here’s a reminder of how we overloaded it using a friend function:

184

CU IDOL SELF LEARNING MATERIAL (SLM)

Now let’s overload the same operator using a member function instead:

You’ll note that this method is pretty similar. However, the member function version of

operator doesn’t take any parameters! Where did the parameter go? In the lesson on the

hidden this pointer, you learned that a member function has an implicit *this pointer which

always points to the class object the member function is working on. The parameter we had

to list explicitly in the friend function version (which doesn’t have a *this pointer) becomes

the implicit *this parameter in the member function version.

Overloading the binary addition (+) operator

Let’s take a look at an example of a binary operator overloaded both ways. First,

overloading operator+ using the friend function:

185

CU IDOL SELF LEARNING MATERIAL (SLM)

Now, the same operator overloaded using the member function method:

Our two-parameter friend function becomes a one-parameter member function, because the

leftmost parameter (cCents) becomes the implicit *this parameter in the member function

186

CU IDOL SELF LEARNING MATERIAL (SLM)

version.Most programmers find the friend function version easier to read than the member

function version, because the parameters are listed explicitly. Furthermore, the friend

function version can be used to overload some things the member function version cannot.

For example, friend operator+(int, cCents) cannot be converted into a member function

because the leftmost parameter is not a class object. However, when dealing with operands

that modify the class itself (e.g. operators =, +=, -=, ++, -, etc…) the member function

method is typically used because C++ programmers are used to writing member functions

(such as access functions) to modify private member variables. Writing friend functions that

modify private member variables of a class is generally not considered good coding style, as

it violates encapsulation.

7.8SUMMARY

Early binding refers to the events that occur at compile time while late

binding means selecting function during the execution. The late binding is

implemented through virtual function.

An abstract base class will not be used to create object, but exist only to act as

a base class Notes of other classes.

Polymorphism allows the program to use the exactly same function name

with exactly same arguments in both a base class and its subclasses. It refers

to the implicit ability of a function to have different meanings in different

contexts.

C++ supports the run time polymorphism with the help of virtual function by

using the concept of dynamic binding. Dynamic binding requires use of

pointers to objects. Pointers to objects of a base class type are compatible

with pointers to objects of a derived class.

Run time polymorphism is achieved only when a virtual function is accessed

through a pointer to the base class. If a virtual function is defined in the base

class, it need not be necessarily redefined in the derived class. Such virtual

187

CU IDOL SELF LEARNING MATERIAL (SLM)

functions (equated to zero) are called pure virtual functions. A class

containing such pure function is called an abstract class.

The keyword operator is used to overload an operator, and the resulting

operator will adopt the meaning supplied by the programmer.

Closely related to operator overloading is the issue of type conversion. Some

conversions take place between user defined types and basic types

Two approaches are used in such conversion: A one argument constructor

changes a basic type to a user defined type, and a conversion operator

converts a user-defined type to a basic type.

When one user-defined type is converted to another, either approach can be

used.

The signature of the function declared as pure virtual in base class must

strictly agree with the signature of the function in child class that implements

the pure virtual function.

The signature of the function declared as pure virtual in base class must

strictly agree with the signature of the function in child class that implements

the pure virtual function.

7.9KEY WORDS/ABBREVIATION

Operator Overloading: Attaching additional meaning and semantics to an operator. It

enables to exhibit more than one operations polymorphically.

Unary Operators: Unary operators operate on one operand (variable or constant). There

are two types of unary operators- increment and decrement.

Abstract Base Class: An abstract base class will not be used to create object, but exist

188

CU IDOL SELF LEARNING MATERIAL (SLM)

only to act as a base class of other classes.

Late Binding: Selecting functions during the execution. Though late binding requires

some overhead it provides increased power and flexibility.

Polymorphism: Polymorphism allows the program to use the exactly same function

name with exactly same arguments in both a base class and its subclasses.

7.10 LEARNINGACTIVITY

1. Which operators are not allowed to be overloaded?

__________________________________________________________________________

__________________________________________________________________________

2. Make function in a class Vehicle may have to make a Vehicle with red color. A class

called Four-wheeler, derived or inherited from Vehicle, may have to use a blue background

and 4 tires as wheels. Write program for this.

__________________________________________________________________

__________________________________________________________________

7.11UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. What will be the output of the following program snippet? Explain.

189

CU IDOL SELF LEARNING MATERIAL (SLM)

2. Create a simple “shape” hierarchy: a base class called Shape and derived classes called

Circle, Square, and Triangle. In the base class, make a virtual function called draw(), and

override this in the derived classes. Make an array of pointers to Shape objects that you

create on the heap (and thus perform upcasting of the pointers), and call draw() through

the base-class pointers, to verify the behavior of the virtual function. If your debugger

supports it, single-step through the code

3. Create an air-traffic control system with base-class Aircraft and various derived types.

Create a Tower class with a vector that sends the appropriate messages to the various

aircraft under its control

4. Write a program which uses a polymorphism with pointers.

5. Create a class that has a data member and a derived class that adds another data member.

Write a non-member function that takes an object of the base class by value and prints

out the size of that object using sizeof. In main( ) create an object of the derived class,

print out its size, and then call your function. Explain what happens

B. Multiple Choice Questions

1. Compile time polymorphism in C++ language is

(a)Operator overloading

(b)Function overloading

(c)Function overriding

(d) a & b

2. C++ abstract class can contain

(a)Pure virtual function

(b)Non-virtual function

(c)Only pure virtual function

190

CU IDOL SELF LEARNING MATERIAL (SLM)

(d)Both pure virtual and non-virtual function

3. False statements about function overloading is

(a)Defining multiple functions with same name in a class is called function overloading

(b)Overloaded function must differ in their order and types of arguments.

(c)Overloaded functions should be preceded with virtual keyword

(d) No statement is false

4. Following keyword is used before a function in a base class to be overridden in derived

class in C++

(a)override

(b)virtual

(c)void

(d) none

5. Which of the following cannot be overloaded in C++?

(a)Increment operator

(b)Constructor

(c)Destructor

(d)New and delete operator

Answers

1. (d), 2. (b), 3. (d), 4. (a), 5. (c)

191

CU IDOL SELF LEARNING MATERIAL (SLM)

7.12SUGGESTED READING

The C++ Programming Language, Bjarne Stroustroup, 3rd edition, Addison Wesley,

1997 2)

C++: The Complete Reference, H. Shildt, 4th edition, TMH, New Delhi, 2004

Thinking in C++, Volume 1, 2nd Edition Bruce Eckel

Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.

http://www.artima.com/cppsource/pure_virtual.html

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=%2Fcom

.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm

http://www.bogotobogo.com/cplusplus

http://www.gamespp.com/c/introductionToCppMetrowerksLesson11.html

Better alternative Run-Time Polymorphism in C++: A practical approach in OO

design for machine intelligence Publisher: IEEE

External Polymorphism An Object Structural Pattern for Transparently Extending

C++ Concrete Data Types Chris Cleeland and Douglas C. Schmidt

192

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT8 EXCEPTION HANDLING

Structure

8.0. LearningObjectives

8.1. Introduction

8.2. Exceptions

8.2.1 Try

8.2.2 Throw

8.2.3 Catch

8.3. Throwing an Exceptions

8.4. Catching an exception

8.5. Summary

8.6. KeyWords/Abbreviations

8.7. LearningActivity

8.8. Unit End Questions (MCQ andDescriptive)

8.9. References

193

CU IDOL SELF LEARNING MATERIAL (SLM)

8.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Explain the basic concepts of exception handling

Discuss Try, Throw, Catch, Throw exceptions

Discuss Throwing and Exception

Discuss Catching an Exception

8.1 INTRODUCTION

When we develop a program, we expect the program does what it is supposed to do without

any error. Many operations, including object instantiation and file processing, are subject to

failures that may go beyond errors. Out-of-memory conditions, for instance, can occur even

when your program is running correctly.

- As an example, for typical application program the highest layer may consist of graphic

user interface (GUI) part that provide interface for users. These high-level components

interact with objects, which in turn encapsulate the application programming interface (API)

routines.

- At a lower level, the API routines may interact with the operating system. The operating

system itself invokes system services that deal with low-level hardware resources such as

physical memory, file systems, and security modules. In general, runtime errors are detected

in these lower code layers should not be handled by themselves.

- To handle an error appropriately, higher-level components have to be informed that an

error has occurred. Generally, error handling consists of detecting an error and notifying the

components that are in charge. These components in turn attempt to recover from the error

or terminate the program properly.

194

CU IDOL SELF LEARNING MATERIAL (SLM)

- From thesimplest one, we may use a proper prompting, for example:

Enter two integer separated by space:

8.2EXCEPTIONS

An exception occurs when an unexpected error or unpredictable behaviors happened on your

program not caused by the operating system itself. These exceptions are handled by code

which is outside the normal flow of control and it needs an emergency exit. - Compared to

the structured exception handling, returning an integer as an error flag is problematic when

dealing with objects. The C++ exception-handling can be a full-fledged object, with data

members and member functions. - Such an object can provide the exception handler with

more options for recovery. A clever exception object, for example, can have a member

function that returns a detailed verbal description of the error, instead of letting the handler

look it up in a table or a file. C++ has incorporated three operators to help us handle these

situations: try, throw and catch. The following is the try, throw…catch program segment

example:

In grammar form:

195

CU IDOL SELF LEARNING MATERIAL (SLM)

8.2.1try

A try block is a group of C++ statements, enclosed in curly braces { }, that might cause an

exception. This grouping restricts the exception handlers to the exceptions generated within

the try block. Each try block may have one or more associated catch blocks. If no exception

is thrown during execution of the guarded section, the catch clauses that follow the try block

are not executed or bypassed. Execution continues at the statement after the lastcatch clause

following the try block in which the exception was thrown. If an exception is thrown during

execution of the guarded section or in any routine the guarded section calls either directly or

indirectly such as functions, an exception object will be created from the object created by

the throw operand. At this point, the compiler looks for a catch clause in a higher execution

context that can handle an exception of the type thrown or a catch handler that can handle

any type of exception. The compound-statement after the try keyword is the guarded section

of code.

syntax for using try/catch as follows −

try {

// protected code

} catch( ExceptionName e1 ) {

// catch block

196

CU IDOL SELF LEARNING MATERIAL (SLM)

} catch( ExceptionName e2 ) {

// catch block

} catch( ExceptionName eN ) {

// catch block

}

8.2.1 throw

The throw statement is used to throw an exception and its value to a matching catch

exception handler. A regular throw consists of the keyword throw and an expression. The

result type of the expression determines which catch block receives control. Within a catch

block, the current exception and value may be re-thrown simply by specifying the throw

keyword alone that is without the expression. The throw is syntactically similar to the

operand of a return statement but here, it returns to the catch handler.

8.2.3catch

A catch block is a group of C++ statements that are used to handle a specific thrown

exception. One or more catch blocks, or handlers, should be placed after each try block. A

catch block is specified by:

1. The keyword catch

2. A catch parameter, enclosed in parentheses (), which corresponds to a specific type of

exception that may be thrown by the try block

3. A group of statements, enclosed in curly braces { }, whose purpose is to handle the

exception The compound-statement after the catch keyword is the exception handler, and

catches or handles the exception thrown by the throw-expression. The exception-declaration

statement part indicates the type of exception the clause handles. The type can be any valid

data type, including a C++ class. - If the exception-declaration statement part is just an

ellipsis (...) such as,

197

CU IDOL SELF LEARNING MATERIAL (SLM)

catch(...)

Then, the catch clause will handle any type of exception, including C exceptions and system

or application generated exceptions such as divide by zero, memory protection and floating-

point violations. Such a handler must be the last handler for its try block acting as default

catch. The catch handlers are examined in order of their appearance following the try block.

If no appropriate handler is found, the next dynamically enclosing try block is examined.

This process continues until the outermost enclosing try block is examined if there are more

than one try block. If a matching handler is still not found, or if an exception occurs while

unwinding, but before the handler gets control, the predefined run-time function terminate()

is called. If an exception occurs after throwing the exception, but before the unwinding

begins, terminate () is also called. The catch block must go right after the try block without

any line of codes between them. The order in which catch handlers appear is important,

because handlers for a given try block are examined in order of their appearance. For

example, it is an error to place the handler for a base class before the handler for a derived

class. After a matching catch handler is found, subsequent handlers are not examined. That

is why an ellipsis catch, catch(...) handler must be the last handler for its try block. Besides

that, catch may be overloaded so that it can accept different types as parameters. In that case

the catch block executed is the one that matches the type of the exception sent through the

parameter of throw Program example:

198

CU IDOL SELF LEARNING MATERIAL (SLM)

Output:

Program example for multiple catch:

199

CU IDOL SELF LEARNING MATERIAL (SLM)

Output

200

CU IDOL SELF LEARNING MATERIAL (SLM)

8.3THROWING AND EXCEPTION

Exceptions can be thrown anywhere within a code block using throw statement. The operand

of the throw statement determines a type for the exception and can be any expression and the

type of the result of the expression determines the type of exception thrown.

Following is an example of throwing an exception when dividing by zero condition occurs

double division (int a, int b) {

if (b == 0) {

throw "Division by zero condition!";

}

return (a/b);

8.4 CATCHING EXCEPTIONS

The catch block following the try block catches any exception. You can specify what type of

exception you want to catch and this is determined by the exception declaration that appears

in parentheses following the keyword catch.

try {

// protected code

} catch(ExceptionName e ) {

// code to handle ExceptionName exception

}

Above code will catch an exception of ExceptionName type. If you want to specify that a

201

CU IDOL SELF LEARNING MATERIAL (SLM)

catch block should handle any type of exception that is thrown in a try block, you must put

an ellipsis, ..., between the parentheses enclosing the exception declaration as follows −

try {

// protected code

} catch(...) {

// code to handle any exception

}

The following is an example, which throws a division by zero exception and we catch it in

catch block.

#include<iostream>

usingnamespace std;

double division(int a,int b){

if( b ==0){

throw"Division by zero condition!";

}

return(a/b);

}

int main (){

int x =50;

int y =0;

202

CU IDOL SELF LEARNING MATERIAL (SLM)

double z =0;

try{

z = division(x, y);

cout << z << endl;

}catch(constchar* msg){

cerr << msg << endl;

}

return0;

}

Because we are raising an exception of type const char*, so while catching this exception,

we have to use const char* in catch block. If we compile and run above code, this would

produce the following result −

Division by zero condition!

8.5 SUMMARY

The exception handling scheme described here is flexible enough to cope with most

synchronous exceptional circumstances. Its semantics are independent of machine

details and can be implemented in several ways optimized for different aspects. In

particular, portable and run-time efficient implementations are both possible. The

exception handling scheme presented here should make error handling easier and less

error-prone.

The try statement allows you to define a block of code to be tested for errors while it

203

CU IDOL SELF LEARNING MATERIAL (SLM)

is being executed.

The throw keyword throws an exception when a problem is detected, which lets us

create a custom error.

The catch statement allows you to define a block of code to be executed, if an error

occurs in the try block.

The try and catch keywords come in pairs:

throw − A program throws an exception when a problem shows up. This is done

using a throw keyword. catch − A program catches an exception with an exception

handler at the place in a program where you want to handle the problem.

The catch keyword indicates the catching of an exception. try − A try block identifies

a block of code for which particular exceptions will be activated. It's followed by one

or more catch blocks

Exception handling is not strictly synonymous with error handling, because the

implementation allows the passing of an exception whether or not an error actually

occurred. You can use exception handlers for things other than handling errors. For

example, you can transfer control back to the original caller of a function. You might

use this if you wanted to process the Quit key in a program and transfer control back

to the driver program when the user types Quit. To do this exception handlers could

be used to throw an object back to the driver.

The exception handling scheme described here is flexible enough to cope with most

synchronous exceptional circumstances. Its semantics are independent of machine

details and can be implemented in several ways optimized for different aspects. In

particular, portable and run-time efficient implementations are both possible. The

exception handling scheme presented here should make error handling easier and less

error-prone.

204

CU IDOL SELF LEARNING MATERIAL (SLM)

8.6KEY WORDS/ABBREVIATIONS

Throw: C++ keyword used to throw (initiate) an exception. See exception handling.

Translation limit: a limit on the size of a source program that a compiler will

accept.

Translation unit: a source file presented to a compiler with an object file produced

as a result.

True:C++ keyword used to specify a value for the bool type.

Exception : object thrown by a throw-statement and (potentially) caught by

an exception handler associated by a try-block.

8.7 LEARNINGACTIVITY

1. Write a program to catch more than two exceptions.

__________________________________________________________________________

__________________________________________________________________________

2. Is the following code block legal?

try {

...

}

Finally

{

205

CU IDOL SELF LEARNING MATERIAL (SLM)

...

}_________________________________________________________________________

__________________________________________________________________________

_

8.8UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Question

1. Create a class with member functions that throw exceptions. Within this class, make

a nested class to use as an exception object. It takes a single char* as its argument;

this represents a description string. Create a member function that throws this

exception. (State this in the function’s exception specification.) Write a try block that

calls this function and a catch clause that handles the exception by printing out its

description string.

2. Prove to yourself that if you create an exception object on the heap and throw the

pointer to that object, it will not be cleaned up.

3. Create a destructor that throws an exception, and write code to prove to yourself that

this is a bad idea by showing that if a new exception is thrown before the handler for

the existing one is reached, terminate( ) is called.

4. Prove to yourself that all exception objects (the ones that are thrown) are properly

destroyed.

5. Track the creation and passing of an exception using a class with a constructor and

copy-constructor that announce themselves and provide as much information as

possible about how the object is being created (and in the case of the copy-

constructor, what object it’s being created from). Set up an interesting situation,

throw an object of your new type, and analyze the program.

206

CU IDOL SELF LEARNING MATERIAL (SLM)

B. Multiple Choice Questions

1. Which is used to handle the exceptions in C++?

(a) catch handler

(b) handler

(c) exception handler

(d) throw

2. Which type of program is recommended to include in try block?

(a) static memory allocation

(b) dynamic memory allocation

(c) const reference

(d) pointer

3. Which statement is used to catch all types of exceptions?

(a) catch()

(b) catch (Test t)

(c) catch (…)

(d) catch (Test)

4. How to handle error in the destructor?

(a) throwing

(b) terminate

(c) both throwing & terminate

207

CU IDOL SELF LEARNING MATERIAL (SLM)

(d) try

5.What kind of exceptions are available in C++?

(a) handled

(b) unhandled

(c) static

(d) dynamic

Answers

1. (c), 2. (b), 3. (c), 4. (b), 5. (b)

8.9REFERENCES

Accelerated C++: Practical Programming by Example by Andrew Koenig and

Barbara E. Mo

C++ Primer (5th Edition) 5th Edition by Stanley B. Lippman, Josee Lajoie, and

Barbara E. Moo

Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and

C++14 (1st Edition) by Scott Meyers

Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and

Solutions by Herb Suttee

https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.ht

https://www.w3schools.com/cpp/cpp_exceptions.asp

https://www.studytonight.com/cpp/exception-handling-in-cpp.php

L. Cardelli, J. Donahue, L. Glassman, M. Jordan, B. Kalsow, G. Nelson: Modula-3

Report. DEC Systems Research Center. August 1988.

Flaviu Cristian: Exception Handling. in Dependability of Resilient Computers, T.

Andersen Editor, BSP Professional Books, Blackwell Scientific Publications, 1989.

Margaret A. Ellis and Bjarne Stroustrup: The Annotated C++ Reference Manual.

Addison Wesley 1990.

J. Goodenough: Exception Handling: Issues and a Proposed Notation. CACM

208

CU IDOL SELF LEARNING MATERIAL (SLM)

December 1975 Steve C. Glassman and Michael J. Jordan: Safe Use of Exceptions.

Personal communication

209

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 9 POINTER & VIRTUAL FUNCTION

Structure

9.0 LearningObjectives

9.1 Introduction

9.2 Understanding Pointers

9.2.1 Pointer Variables

9.3 Declaring pointers

9.3.1 Accessing Address of Variable

9.3.2 Pointer Expressions

9.3.3 Pointer Initialization

9.3.3.1 The this Pointer

9.4 Pointer to Pointer

9.5 pointer to derived classes

9.6 Virtual Functions

9.6.1 Static and dynamic binding

9.7 Summary

9.8 KeyWords/Abbreviations

9.9 LearningActivity

9.10 Unit End Questions (MCQ andDescriptive)

9.11 References

210

CU IDOL SELF LEARNING MATERIAL (SLM)

9.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Identify the understanding pointers

Demonstrate the accessing address of a variable

Recognize the declaring and initializing pointers

Describe the pointer to pointer

Explain the pointer to a function

Explain static and dynamic binding.

9.1 INTRODUCTION

Computers use their memory for storing instructions of the programs and the values of the

variables. Memory is a sequential collection of storage cells. Each cell has an address

associated with it. Whenever we declare a variable, the system allocates, somewhere in the

memory, a memory location and a unique address is assigned to this location.

9.2 UNDERSTANDING POINTERS

Pointer is a variable which can hold the address of a memory location rather than the value

at the location. Consider the following statement:

int num = 84;

This statement instructs the system to reserve a 2-byte memory location and puts the value

84 in that location. Assume that a system allocates memory location 1001 for num.

Diagrammatically, it can be shown as:

211

CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 9.1Two byte memory location

As the memory addresses are numbers, they can be assigned to some other variable. Let ptr

be the variable which holds the address of variable num. Thus, we can access the value of

num by the variable ptr. Thus, we can say “ptr points to num”. Diagrammatically, it can be

shown as

Fig 9.2 Pointer two numbers

Pointers help in allocating memory dynamically. Pointers improve execution time and saves

space

9.2.1Pointer Variables

Pointers are variables that follow all the usual naming rules of regular, non-pointer variables.

As with regular variables, you must declare pointer variables before you use them. A type of

pointer exists for every data type in C++; you can use integer pointers, characters pointers,

floating-point pointers, floating-point pointer, and so on. You can declare global pointer or

local pointer, depending on where you declare them. The only difference between pointer

variables and regular variables is what they hold. Pointer does not contain values, but the

address of a value. C++ has two operators:

212

CU IDOL SELF LEARNING MATERIAL (SLM)

1. & - The “address of” operator

2. * - The de-referencing operator

Whenever you see ‘&’ used with pointer, think of the phrase “address of”. The ‘&’ operator

provides the memory address of whatever variable it precedes. The * operator, when used

withpointer, de-references the pointer’s value. When you see * operator used, think of the

phrase Notes “value pointed to”.

9.3 DECLARING POINTERS

A pointer is a special variable that return the address of a memory. If you need to declare a

variable to hold your age, you might use the following variable declaration:

int age = 18 //

declares to variable to hold my age Declaring age this way does several things. Because C++

knows that you need a variable called age, C++ reserves storage for that variable. C++ also

knows that you will store only integers in age, not floating-point or double floating point

data. You also have requested that C++ store the value of 18 in age after reserving storage

for that variable. Suppose that you want to declare a pointer variable, not to hold your age

but to point to age, the variable that hold your age. p_age might be a good name for this

pointer variable. Figure given below shows an illustration of what you want to do. This

example assumes that C++ store age at address 1002, although your C++ compiler arbitrarily

determines the address of age, and it could be anything.

To declare the p_age pointer variable

You should do the following:

int*_age; // declare an integer pointer

As with the declaration for age, this line reserves a variable called p_age. It is not a normal

integer variable, however, because of the C++ knows that this variable is to be a pointer

213

CU IDOL SELF LEARNING MATERIAL (SLM)

variable.

9.3Page Contains the Address of Age; p_age to the Age Variable

Example:

9.3.1 Accessing Address of Variable

Consider the following statements:

int q, * i, n;

q = 35;

i = & q;

n = * i;

214

CU IDOL SELF LEARNING MATERIAL (SLM)

i is a pointer to an integer containing the address of q. In the fourth statement we have

assigned the value at address contained in i to another variable n. Thus, indirectly we have

accessed the variable q through n using pointer variable i.

9.3.2 Pointer Expressions

Like other variables, pointer variables can be used in expressions. Arithmetic and

comparison operations can be performed on the pointers

Example: If p1 and p2 are properly declared and initialized pointers, then following

statements are valid.

y = * p1 * *p2;

sum = sum + * p1;

9.3.3 Pointer Initialization

When declaring pointers we may want to explicitly specify which variable we want them to

point to:

int number;

int *tommy = &number;

The behavior of this code is equivalent to:

int number;

int *tommy;

tommy = &number;

When a pointer initialization takes place we are always assigning the reference value to

where the pointer points (tommy), never the value being pointed (*tommy). You must

consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is a

pointer, it is not the dereference operator (although both use the same sign: *). Remember,

215

CU IDOL SELF LEARNING MATERIAL (SLM)

they are two different functions of one sign. Thus, we must take care not to confuse the

previous code with:

int number;

int *tommy;

*tommy = &number;

that is incorrect, and anyway would not have much sense in this case if you think about it.

As in the case of arrays, the compiler allows the special case that we want to initialize the

content at which the pointer points with constants at the same moment the pointer is

declared:

char * terry = “hello”;

In this case, memory space is reserved to contain “hello” and then a pointer to the first

character of this memory block is assigned to terry. If we imagine that “hello” is stored at

the memory locations that start at addresses 1702, we can represent the previous declaration

as:

9.4 pointer declaration

It is important to indicate that terry contains the value 1702, and not ‘h’ nor “hello”,

although 1702 indeed is the address of both of these. The pointer terry points to a sequence

of characters and can be read as if it was an array (remember that an array is just like a

216

CU IDOL SELF LEARNING MATERIAL (SLM)

constant pointer).

Example:

We can access the fifth element of the array with any of these two expressions:

*(terry+4) terry

[4]

Both expressions have a value of ‘o’ (the fifth element of the array)

9.3.3.1The this Pointer

C++ uses a unique keyword called “this” to represent an object that invokes a member

function. ‘this’ is a pointer that points to the object on which this funct ion was called. The

pointer ‘this’ acts as an implicit argument to all the member function apart from the explicit

arguments passed to it.When a number of objects are created from the same class each

object’s data members are created as separate copies. However, only a single copy of

methods is retained in the memory. That is all objects of a class share a single copy of the

compiled class functions. A particular object is referenced by “this” pointer

internally.Consider the following code snippet

217

CU IDOL SELF LEARNING MATERIAL (SLM)

When the code is executed, two marks variables are created - one for vibhor and one for

prashant, but only one copy of setMarks function is kept in the memory (see the figure

below).

Fig 9.5 Use of this pointer

9.4 POINTER TO POINTERS

218

CU IDOL SELF LEARNING MATERIAL (SLM)

Pointer is a variable, which contains address of a variable. This variable itself could be

another pointer. Thus, a pointer contains another pointer’s address as shown in the example

given below:

The following figure would help you in tracing out how a program prints the output

Output:

Address of i = 6485

Address of i = 6485

Address of i = 6485

219

CU IDOL SELF LEARNING MATERIAL (SLM)

Address of j = 3276

Address of j = 3276

Address of k = 7234

Value of j = 6485

Value of k = 3276

Value of i = 3

Value of i = 3

Value of i = 3

Value of i = 3

9.5POINTER TO DERIVED CLASSES

In C++, we can declare a pointer points to the base class as well as derive class.

Consider below example to understand pointer to derived class

Program

#include<iostream.h>

class base

{

public:

int n1;

void show()

{

cout<<”\nn1 = “<<n1;

}

220

CU IDOL SELF LEARNING MATERIAL (SLM)

};

class derive : public base

{

public:

int n2;

void show()

{

cout<<”\nn1 = “<<n1;

cout<<”\nn2 = “<<n2;

}

};

int main()

{

base b;

base *bptr; //base pointer

cout<<”Pointer of base class points to it”;

bptr=&b; //address of base class

bptr->n1=44; //access base class via base pointer

bptr->show();

derive d;

cout<<”\n”;

bptr=&d; //address of derive class

bptr->n1=66; //access derive class via base pointer

bptr->show();

return 0;

}

Output

Pointer of base class points to it

n1 = 44

221

CU IDOL SELF LEARNING MATERIAL (SLM)

Pointer of base class points to derive class

n1=66

Here the show() method is the overridden method, bptr execute show() method of ‘base’

class twice and display its content. Even though bptr first points to ‘base’ and second time

points to ‘derive’ ,both the time bptr->show() executes the ‘base’ method show()

9.6 VIRTUAL FUNCTION

Virtual functions, one of advanced features of OOP is one that does not really exist but it

appears real in some parts of a program. This section deals with the polymorphic features

which are incorporated using the virtual functions. The general syntax of the virtual function

declaration is:

class use_defined_name

{

private:

public:

virtual return_type function_name1 (arguments);

virtual return_type function_name2(arguments);

virtual return_type function_name3( arguments);

———————

———————

};

To make a member function virtual, the keyword virtual is used in the methods while it is

declared in the class definition but not in the member function definition. The keyword

222

CU IDOL SELF LEARNING MATERIAL (SLM)

virtual precedes the return type of the function name. The compiler gets information from

the keyword virtual that it is a virtual function and not a conventional function declaration.

Example: The following declaration of the virtual function is valid

Remember that the keyword virtual should not be repeated in the definition if the definition

occurs outside the class declaration. The use of a function specifier virtual in the function

definition is invalid.

A virtual function cannot be a static member since a virtual member is always a member of a

particular object in a class rather than a member of the class as a whole.

9.6.1 Static and dynamic binding

Static Binding: By default, matching of function call with the correct function definition

223

CU IDOL SELF LEARNING MATERIAL (SLM)

happens at compile time. This is called static binding or early binding or compile-time

binding. Static binding is achieved using function overloading and operator overloading.

Even though there are two or more functions with same name, compiler uniquely identifies

each function depending on the parameters passed to those functions.

Program to illustrate early binding.

// Any normal function call (without virtual)

// is binded early. Here we have taken base

// and derived class example so that readers

// can easily compare and see difference in

// outputs.

#include<iostream>

using namespace std;

class Base

{

public:

void show() { cout<<" In Base \n"; }

};

class Derived: public Base

{

public:

224

CU IDOL SELF LEARNING MATERIAL (SLM)

void show() { cout<<"In Derived \n"; }

};

int main(void)

{

Base *bp = new Derived;

// The function call decided at

// compile time (compiler sees type

// of pointer and calls base class

// function.

bp->show();

return 0;

}

Output:

In Base

Dynamic Binding: C++ provides facility to specify that the compiler should match function

calls with the correct definition at the run time; this is called dynamic binding or late binding

or run-time binding. Dynamic binding is achieved using virtual functions. Base class pointer

points to derived class object. And a function is declared virtual in base class, then the

matching function is identified at run-time using virtual table entry.

225

CU IDOL SELF LEARNING MATERIAL (SLM)

CPP Program to illustrate late binding

#include<iostream>

using namespace std;

class Base

{

public:

virtual void show() { cout<<" In Base \n"; }

};

class Derived: public Base

{

public:

void show() { cout<<"In Derived \n"; }

};

int main(void)

{

Base *bp = new Derived;

bp->show(); // RUN-TIME POLYMORPHISM

return 0;

}

Output:

226

CU IDOL SELF LEARNING MATERIAL (SLM)

In Derived

9.7 SUMMARY

A pointer is a variable that holds the memory address of the location of

another variable in memory. A pointer is declared in the following form:

type * var_name ;

where type is a predefined C++ data type and var_name is the name

of the pointer variable

The operator &, when placed before a variable, returns the memory

address of its operand. The operator * returns the memory address of its

operand.

The operator * returns the data value stored in the area being pointed to

by the pointer following it.

The pointer variables must always point to the correct type of data.

Pointers must be initialized properly because uninitialized pointers result

in the system crash.

In pointer arithmetic, all pointers increase and decrease by the length of

the data type point to.

227

CU IDOL SELF LEARNING MATERIAL (SLM)

An array name is a pointer that stores the address of its first element. If

the array name is incremented, It actually points to the next element of the

array. Array of pointers makes more efficient use of available memory.

Generally, it consumes lesser bytes than an equivalent multi-dimensional

array.

Functions can be invoked by passing the values of arguments or

references to arguments or pointers to arguments.

When references or pointers are passed to a function, the function works

with the original copy of the variable. A function may return a reference

or a pointer also.

Virtual functions do not really exist but it appears real in some parts of a

program. To make a member function virtual, the keyword virtual is used

in the methods while it is declared in the class definition but not in the

member function definition.

Early binding refers to the events that occur at compile time while late

binding means selecting function during the execution. The late binding is

implemented through virtual function.

9.8KEY WORDS/ABBREVIATIONS

Base Address: Starting address of a memory location holding array elements.

Function Pointer: A function may return a reference or a pointer variable also. A

pointer to a function is the address where the code for the function resides. Pointer to

functions can be passed to functions, returned from functions, stored in arrays and

assigned to other pointers. Memory location: A container that can store a binary

number.

Pointer: A variable holding a memory address.

228

CU IDOL SELF LEARNING MATERIAL (SLM)

Late Binding: Selecting functions during the execution. Though late binding

requires some overhead it provides increased power and flexibility.

Virtual Function: Virtual functions, one of advanced features of OOP is one that

does not really exist but it appears real in some parts of a program

9.9LEARNINGACTIVITY

1. WAP that demonstrates dynamic binding.

__________________________________________________________________________

__________________________________________________________________________

2. WAP that demonstrates pointer to derived classes

__________________________________________________________________________

__________________________________________________________________________

9.10UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1 Write a small program to show the difference between calling a virtual function

inside a normal member function and calling a virtual function inside a

constructor. The program should prove that the two calls produce different results.

2 In Early.cpp, how can you tell whether the compiler makes the call using early or

late binding? Determine the case for your own compiler.

3 In AddingVirtuals.cpp, make all the member functions of Pet pure virtual, but

provide a definition for name( ). Fix Dog as necessary, using the base-class

definition of name( ).

4 Create a class that has a data member and a derived class that adds another data

member. Write a non-member function that takes an object of the base class by

229

CU IDOL SELF LEARNING MATERIAL (SLM)

value and prints out the size of that object using sizeof. In main( ) create an object

of the derived class, print out its size, and then call your function. Explain what

happens.

5 Create a simple example of a virtual function call and generate assembly output.

Locate the assembly code for the virtual call and trace and explain the code

B. Multiple Choice Questions

1. Which class is used to design the base class?

(a) abstract class

(b) derived class

(c) base class

(d) derived & base class

2. Which is used to create a pure virtual function?

(a) $

(b) =0

(c) &

(d)!

3. Which is also called as abstract class?

(a) virtual function

(b) pure virtual function

(c) derived class

(d) base class

4. What is meant by pure virtual function?

(a) Function which does not have definition of its own

(b) Function which does have definition of its own

(c) Function which does not have any return type

(d) Function which does not have any return type & own definition

5. Where does the abstract class is used?

230

CU IDOL SELF LEARNING MATERIAL (SLM)

(a) base class only

(b) derived class

(c) both derived & base class

(d) virtual class

Answers

1. (a), 2. (b), 3. (b), 4. (a), 5(a)

9.11 REFERENCES

Horstman (2003). Computing Concept with C++ Essentials. New Delhi: John Wiley.

Easttom C. (2010). C++ Programming Fundamentals. Delhi: Firewall Media.

Programming in C++” by Mahapatra P B

Object-Oriented Programming with C++” by A K Sharma

Amma, Helm, Johnson, Vlissides (GoF) – Design Patterns Elements of Reusable

Object-Oriented Software

Herb Sutter – Exceptional C++: 47 Engineering Puzzles, Programming Problems,

and Solutions

Object Oriented Programming with C++; Cyber tech publications

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101 index.jsp?topic=

%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm

http://www.cplusplus.com/doc/tutorial/pointers/

http://www.artima.com/cppsource/pure_virtual.html

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=

%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm

https://codescracker.com/cpp/cpp-declaring-initializing-pointers.htm

https://www.xspdf.com/resolution/52190469.html

https://www.geeksforgeeks.org/pointers-c-examples/

Scott Meyers – Effective C++: 55 Specific Ways to Improve Your Programs and

231

CU IDOL SELF LEARNING MATERIAL (SLM)

Designs

Scott Meyers – More Effective C++: 35 New Ways to Improve Your Programs and

Designs

UNIT 10 DYNAMIC MEMORY ALLOCATION

Structure

10.0 LearningObjectives

10.1 Introduction

10.2 Dynamic memory allocation

10.3 New and Delete operator

10.3.1 Operators new and new[ ]

10.3.2 Operators n delete and delete [ ]

10.4 Summary

10.5 KeyWords/Abbreviations

10.6 LearningActivity

10.7 Unit End Questions (MCQ andDescriptive)

10.8 Suggested Readings

10.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

232

CU IDOL SELF LEARNING MATERIAL (SLM)

Discuss the dynamic memory management

Explain Dynamic memory allocation using new and delete operator

10.1 INTRODUCTION

Dynamic memory allocation using new and delete operator. A good understanding of how

dynamic memory really works in C++ is essential to becoming a good C++ programmer.

Memory in your C++ program is divided into two parts −

The stack − All variables declared inside the function will take up memory from the stack.

The heap − this is unused memory of the program and can be used to allocate the memory

dynamically when program runs

Many times, you are not aware in advance how much memory you will need to store

particular information in a defined variable and the size of required memory can be

determined at run time. You can allocate memory at run time within the heap for the variable

of a given type using a special operator in C++ which returns the address of the space

allocated. This operator is called new operator. If you are not in need of dynamically

allocated memory anymore, you can use delete operator, which de-allocates memory

previously allocated by new operator.

10.2DYNAMIC MEMORY ALLOCATION

Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as

below:

ptr=new DataType (initializer);

Here,

233

CU IDOL SELF LEARNING MATERIAL (SLM)

1. ptr is a valid pointer of type DataType.

2. DataType is any valid C++ data type.

3. Initializer (optional) if given, the newly allocated variable is initialized to that

value.

Example: //Example Program in C++

This is will allocate memory for an int(eger) having initial value 10, pointed by the ptr

pointer. Memory space for arrays is allocated as shown below:

ptr=new DataType [x];

Here,

1. ptr and DataType have the same meaning as above.

2. x is the number of elements and C is a constant.

Example:

234

CU IDOL SELF LEARNING MATERIAL (SLM)

10.3 NEW AND DELETE OPERATOR

Until now, in all our programs, we have only had as much memory available as we declared

for our variables, having the size of all of them to be determined in the source code, before

the execution of the program. But, what if we need a variable amount of memory that can

only be determined during runtime? For example, in the case that we need some user input

to determine the necessary amount of memory space. The answer is dynamic memory, for

which C++ integrates the operators new and delete.

10.3.1 Operators new and new[]

In order to request dynamic memory we use the operator new. New is followed by a data

type specifier and – if a sequence of more than one element is required – the number of these

within brackets [ ]. It returns a pointer to the beginning of the new block of memory

allocated. Its form is:

pointer = new type

pointer = new type [number_of_elements]

235

CU IDOL SELF LEARNING MATERIAL (SLM)

The first expression is used to allocate memory to contain one single element of type type.

The Notes second one is used to assign a block (an array) of elements of type type, where

number_of_elements is an integer value representing the amount of these. For example:

int * bobby;

bobby = new int [5];

In this case, the system dynamically assigns space for five elements of type int and returns a

pointer to the first element of the sequence, which is assigned to bobby.

Fig 10.1Space for five elements

The first element pointed by bobby can be accessed either with the expression bobby[0]

or the expression *bobby. Both are equivalent as has been explained in the section about

pointers. The second element can be accessed either with bobby[1] or *(bobby+1)

and so on... You could be wondering the difference between declaring a normal array and

assigning dynamic memory to a pointer, as we have just done. The most important

difference is that the size of an array has to be a constant value, which limits its size to what

we decide at the moment of designing the program, before its execution, whereas the

dynamic memory allocation allows us to assign memory during the execution of the program

(runtime) using any variable or constant value as its size. The dynamic memory requested by

our program is allocated by the system from the memory heap. However, computer memory

is a limited resource, and it can be exhausted. Therefore, it is important to have some

mechanism to check if our request to allocate memory was successful or not. C++ provides

two standard methods to check if the allocation was successful: One is by handling

exceptions. Using this method an exception of type bad_alloc is thrown when the allocation

fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now

you should know that if this exception is thrown and it is not handled by a specific handler,

236

CU IDOL SELF LEARNING MATERIAL (SLM)

the program execution is terminated. This exception method is the default method used by

new, and is the one used in a declaration like:

bobby = new int [5]; //

if it fails an exception is thrown The other method is known as nothrow, and what happens

when it is used is that when a memory allocation fails, instead of throwing a bad_alloc

exception or terminating the program, the pointer returned by new is a null pointer, and the

program continues its execution. This method can be specified by using a special object

called nothrow, declared in header , as argument fornew:

bobby = new (nothrow) int [5];

The first element pointed by bobby can be accessed either with the expression bobby[0]

or the expression *bobby. Both are equivalent as has been explained in the section about

pointers. The second element can be accessed either with bobby[1] or *(bobby+1)

and so on... You could be wondering the difference between declaring a normal array and

assigning dynamic memory to a pointer, as we have just done. The most important

difference is that the size of an array has to be a constant value, which limits its size to what

we decide at the moment of designing the program, before its execution, whereas the

dynamic memory allocation allows us to assign memory during the execution of the program

(runtime) using any variable or constant value as its size. The dynamic memory requested by

our program is allocated by the system from the memory heap. However, computer memory

is a limited resource, and it can be exhausted. Therefore, it is important to have some

mechanism to check if our request to allocate memory was successful or not. C++ provides

two standard methods to check if the allocation was successful: One is by handling

exceptions. Using this method an exception of type bad_alloc is thrown when the allocation

fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now

you should know that if this exception is thrown and it is not handled by a specific handler,

the program execution is terminated. This exception method is the default method used by

new, and is the one used in a declaration like:

237

CU IDOL SELF LEARNING MATERIAL (SLM)

bobby = new int [5]; //

if it fails an exception is thrown The other method is known as nothrow, and what happens

when it is used is that when a memory allocation fails, instead of throwing a bad_alloc

exception or terminating the program, the pointer returned by new is a null pointer, and the

program continues its execution. This method can be specified by using a special object

called nothrow, declared in header , as argument In this case, if the allocation of this block

of memory failed, the failure could be detected by checking if bobby took a null pointer

value:

int * bobby; bobby = new (nothrow) int [5];

if (bobby == 0) {

// error assigning memory. Take measures.

};

Anyway this method can become tedious for larger projects, where the exception method is

generally preferred.

10.3.2 Operators delete and delete[ ]

Since the necessity of dynamic memory is usually limited to specific moments within a

program, once it is no longer needed it should be freed so that the memory becomes

available again for other requests of dynamic memory. This is the purpose of the operator

delete, whose format is: delete pointer;

delete [ ] pointer;

The first expression should be used to delete memory allocated for a single element, and the

second one for memory allocated for arrays of elements. The value passed as argument to

delete must be either a pointer to a memory block previously allocated with new, or a null

pointer (in the case of a null pointer, delete produces no effect).

238

CU IDOL SELF LEARNING MATERIAL (SLM)

Enter number : 75

Enter number : 436

239

CU IDOL SELF LEARNING MATERIAL (SLM)

Enter number : 1067

Enter number : 8

Enter number : 32

You have entered: 75, 436, 1067, 8, 32,

Notice how the value within brackets in the new statement is a variable value entered by the

user (i), not a constant value:

p= new (nothrow) int[i];

But the user could have entered a value for i so big that our system could not handle it. For

example, when I tried to give a value of 1 billion to the “How many numbers” question, my

system could not allocate that much memory for the program and I got the text message we

prepared for this case (Error: memory could not be allocated). It is a good practice to always

check if a dynamic memory block was successfully allocated. Therefore, if you use the

nothrow method, you should always check the value of the pointer returned. Otherwise, use

the exception method, even if you do not handle the exception. This way, the program will

terminate at that point without causing the unexpected results of continuing executing a code

that assumes a block of memory to have been allocated when in fact it has not.

10.4 SUMMARY

Dynamic memory allocation in C/C++ refers to performing memory

allocation manually by programmer. Dynamically allocated memory is allocated on

Heap and non-static and local variables get memory allocated on Stack

There are essentially two types of memory allocation Static – Done by the compiler

automatically (implicitly).

Global variables or objects -- memory is allocated at the start of the program, and

freed when program exits; alive throughout program execution

Can be access anywhere in the program.

240

CU IDOL SELF LEARNING MATERIAL (SLM)

Local variables (inside a routine) – memory is allocated when the routine starts and

freed when the routine returns.

A local variable cannot be accessed from another routine.

Allocation and free are done implicitly.

No need to explicitly manage memory is nice (easy to work with), but has

limitations! Using static allocation, the array size must be fixed.

There are essentially two types of memory allocation

Dynamic memory allocation deals with this situation. Dynamic – Done explicitly

by programmer.

Programmer explicitly requests the system to allocate memory and return starting

address of memory allocated (what is this?). This address can be used by the

programmer to access the allocated memory. When done using memory, it must

be explicitly freed.

the ‘delete’ Operator - Used to free memory allocated with new operator

The delete operator should be called on a pointer to dynamically allocated memory

when it is no longer needed

You can change the behavior of new and delete if they don’t suit your needs,

particularly if they aren’t efficient enough. Also, you can modify what happens when

the heap runs out of storage.

10.5KEY WORDS/ABBREVIATIONS

Memory location: A container that can store a binary number.

Pointer: A variable holding a memory address.

Reference: An alias for a pointer that does not require de-referencing to use

Delete operator: C++ keyword and operator used to delete dynamic storage.

Delete [] operator: used to delete array objects.

Deallocation: the processing of freeing memory space previously used by an object

241

CU IDOL SELF LEARNING MATERIAL (SLM)

10.6LEARNINGACTIVITY

1. Write a program that reads a group of numbers from the user and places them in an array

of type float. Once the numbers are stored in the array, the program should average them and

print the result. Use pointer notation wherever possible.

__________________________________________________________________________

__________________________________________________________________________

2. WAP to understand the concept of new and delete operator.

__________________________________________________________________________

__________________________________________________________________________

10.7 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1. Create a program, which reads an n dimensional vector v of doubles and reads A an n

× n matrix (linear transformation) and prints the resulting vector after applying the

transformation A (ie, A × v). n, the dimension, should also be read from the

keyboard, and A and v should be dynamically allocated.

2. Modify a procedure, which returns a pointer to the transpose of an n×m dynamically

allocated matrix.

3. Create a vector< Counted*> and fill it with pointers to new Counted objects (from

Exercise 1). Move through the vector and print the Counted objects, then move

through again and delete each one.

4. Create an object of class Counted(from Exercise 1) using new, cast the resulting

pointer to a void*, and delete that. Explain the results.

5. Create a class Counted that contains an int id and a static int coun. The default

constructor should begin: t Counted( ) : id(count++). It should also print its { id and

242

CU IDOL SELF LEARNING MATERIAL (SLM)

that it’s being created. The destructor should print that it’s being destroyed and its id.

Test your class

B. Multiple Choice Questions

1. Local variables are stored in an area called ___________

(a) Heap

(b) Permanent storage area

(c) Free memory

(d) Stack

2. Choose the statement which is incorrect with respect to dynamic memory allocation.

(a) Memory is allocated in a less structured area of memory, known as heap

(b) Used for unpredictable memory requirements

(c) Execution of the program is faster than that of static memory allocation

(d) Allocated memory can be changed during the run time of the program based on the

requirement of the program

3. Which of the following header files must necessarily be included to use dynamic memory

allocation functions?

(a) stdlib.h

(b) stdio.h

(c) memory.h

(d) dos.h

4. Which of the following is an example for nonlinear data type?

(a) Tree

(b) Array

(c) Linked list

(d) Queue

5. Queue data structure works on the principle of ____________

243

CU IDOL SELF LEARNING MATERIAL (SLM)

(a) Last in First Out (LIF0)

(b) First in Last Out (FILO)

(c) First in First Out (FIFO)

(d) Last in Last Out (LILO)

Answers

1. (d), 2. (c), 3. (a), 4. (a), 5. (c)

10.8 REFERENCES

Modern C++ Design: Generic Programming and Design Patterns Applied

More Effective C++by Scott Meyers

Effective C++: 55 Specific Ways to Improve Your Programs and Designs

by Scott Meyers

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices

by Herb Sutter

https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic-

memory/

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=

%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm

http://www.cplusplus.com/doc/tutorial/dynamic/

https://fresh2refresh.com/cpp-tutorial/cpp-dynamic-memory-allocation/

Dynamic Memory Allocation: Role in Memory Management March

2014Authors:Prabhudev Irabashetti

Memory Management Techniques: Static and Dynamic Memory

AllocationAuthor : Supriya Pralhad Mali, Sonali Dohe and Priya RangdaPages : 92-

94

Review Of Memory Allocation And Management In Computer Systems Ahmed

Faraz

244

CU IDOL SELF LEARNING MATERIAL (SLM)

245

CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 11 FILES

Structure

11.0. LearningObjectives

11.1. Introduction

11.2. Concept of Streams

11.3. Hierarchy of Console Stream Classes

11.4. File operations

11.5. Unformatted I/O Operations

11.6. Reading/Writing of files

11.7. Summary

11.8. KeyWords/Abbreviations

11.9. LearningActivity

11.10.Unit End Questions (MCQ andDescriptive)

11.11. References

11.0 LEARNINGOBJECTIVES

After studying this unit, you will be able to:

Recognize the concepts of streams

Describe the hierarchy of console stream classes

Explain the unformatted I/O operations

Unformatted I/O Operations

Explain Reading/Writing of files.

246

CU IDOL SELF LEARNING MATERIAL (SLM)

11.1 INTRODUCTION

One of the most essential features of interactive programming is its ability to interact with

the users through operator console usually comprising keyboard and monitor. Accordingly,

every computer language (and compiler) provides standard input/output functions and/or

methods to facilitate console operations. C++ accomplishes input/output operations using

concept of stream. A stream is a series of bytes whose value depends on the variable in

which it is stored. This way, C++ is able to treat all the input and output operations in a

uniform manner. Thus, whether it is reading from a file or from the keyboard, for a C++

program it is simply a stream. We have used the objects cin and cout (predefined in the

iostream.h file) for the input and output of data of various types. This has been made

possible by overloading the operators >> and << to recognize all the basic C++ types. The

>> operator is overloaded in the istream class and << is overloaded in the ostream class. The

following is the general format for reading data from the keyboard:

cin >> variable1 >> variable2 >>.. ...>> variableN;

where variable1, variable2, . . .. are valid C++ variable names that have been declared

already. Notes This statement will cause the computer to halt the execution and look for

input data from the keyboard. The input data for this statement would be: datal

data2……dataN The input data are separated by white spaces and should match the type of

variable in the cin list. Spaces, new lines and tabs will be skipped. The operator >> reads the

data character by character and assigns it to the indicated location. The reading for a variable

will be terminated at the encounter of a white space or a character that does not match the

destination type. For example, consider the following code:

int code;

cin >> code;

Suppose the following data is given as input:

247

CU IDOL SELF LEARNING MATERIAL (SLM)

1267E

The operator will read the characters up to 7 and the value 1267 is assigned to code. The

character E remains in the input stream and will be input to the next cin statement. The

general format of outputting data:

cout << iteml <<< .. ..<< itemN;

11.2 CONCEPT OF STREAMS

A stream is a source of sequence of bytes. A stream abstracts for input/output devices. It can

be tied up with any I/O device and I/O can be performed in a uniform way. The C++

iostream library is an object-oriented implementation of this abstraction. It has a source

(producer) of flow of bytes and a sink (consumer) of the bytes. The required classes for the

stream I/O are defined in different library header files. To use the I/O streams in a C++

program, one must include iostream.h header file in the program. This file defines the

required classes and provides the buffering. Instead of functions, the library provides

operators to carry out the I/O. Two of the Stream Operators are:

<< : Stream insertion for output.

>> : Stream extraction for input. The following streams are created and opened

automatically:

cin: Standard console input (keyboard).

cout: Standard console output (screen).

cprn : Standard printer (LPT1).

cerr : Standard error output (screen).

clog : Standard log (screen).

caux: Standard auxiliary (screen).

248

CU IDOL SELF LEARNING MATERIAL (SLM)

Example: The following program reads an integer and prints the input on the console

11.3 HIERARCHY OF CONSOLE STREAM CLASSES

Streams can also be tied up with data files. The required stream classes for file I/O are

defined in fstream.h and/or strstream.h. fstream : File I/O class.

Table 11.1 fstream : File I/O class

249

CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 11.1 Hierarchy of file stream classes

There are some special functions that can alter the state the stream. These functions are

called manipulators. Stream manipulators are defined in iomanip.h.

Table 11.1 Stream manipulators

dec Sets base 10 integers.

endl Sends a new line character.

ends Sends a null (end of string) character.

flush Flushes an output stream.

fixed Sets fixed real number notation.

hex Sets base 16 integers.

Oct Sets base 8 integers.

ws Discard white space on input.

setbase(int)Sets integer conversion base (0, 8, 10 or 16 where0 sets base 10).

setfill(int) Sets fill character

250

CU IDOL SELF LEARNING MATERIAL (SLM)

setiosflags(long) Sets format state as specified by argument

setw(int) Sets field width.

resetiosflags(long) Clears format state as specified by argument

The stream classes have a variety of member functions to give them their required

functionalities. Thus, there is a function to open the stream, one for reading/writing, one for

closing the stream and the like. The stream class member functions are listed below

Table 11.2The stream class member functions

Continued…

251

CU IDOL SELF LEARNING MATERIAL (SLM)

Table 11.2The stream class member function

10.4 FILE OPERATIONS

A file may be opened for a number of file operations. The corresponding stream must be set

with the intended operation. The different file stream modes are indicated by File Access

Flags as listed below:

11.3File Access Flags

This program displays use of different stream manipulators.

252

CU IDOL SELF LEARNING MATERIAL (SLM)

The output of the program:

Decimal…………….100

Hexadecimal…………6

Octal………………..144

The put() and get() Functions

The classes istream and ostream define two member functions get() and put() respectively to

handle the single character input/output operations. There are two types of get() functions.

We can use both get(char*) and get(void) prototypes to fetch a character including the blank

space, tab and the newline character. The get(char*) version assigns the input character to its

argument and the get(void) version returns the input character. . . Since these functions are

253

CU IDOL SELF LEARNING MATERIAL (SLM)

members of the input/output stream classes, we must invoke them using an appropriate

object. For instance, look at the code snippet given below:

char c; cin.get(c); //get a character from keyboard and assign

it to c

while (c!= ‘\n’)

{

cout << c; //display the character on screen cin.get (c);

//get another character

}

This code reads and displays a line of text (terminated by a newline character). Remember,

the operator>>can also be used to read a character but it will skip the white spaces and

newline character. The above while loop will not work properly if the statement. cin >> c; is

used in place of

cin.get(c);

Try using both of them and compare the results. The get(void) version is used as follows:

char c; c = cin.get(); //cin.get(c) replaced

The value returned by the function get() is assigned to the variable c. The function put(), a

member of ostream class, can be used to output a line of text, character by character. For

example,

cout << put(‘x’);

displays the character x and

cout << put(ch); displays the value of variable ch.

The variable ch must contain a character value. We can also use a number as an argument to

254

CU IDOL SELF LEARNING MATERIAL (SLM)

the function put (). For example,

cout << put(68);

displays the character D. This statement will convert the int value 90 to a char value and

display the character whose ASCII value is 68. The following segment of a program reads a

line of text from the keyboard and displays it on the screen.

char c; cin.get (c); //read a character while(c!= ‘\n’)

{

cout << put(c); //display the character on screen cin.get (c

);

The getline () and write () Functions

We can read and display a line of text more efficiently using the line-oriented input/output

functions getline() and write(). The getline() function reads a whole line of text that ends

with a newline character. This function can be invoked by using the object cin as follows:

cin.getline(line, size);

This function call invokes the function which reads character input into the variable line.

The reading is terminated as soon as either the newline character ‘\n’ is encountered or size

number of characters are read (whichever occurs first). The newline character is read but not

saved. Instead, it is replaced by the null character. For example; consider the following code:

char name[20];

cin.getline(name, 20);

Assume that we have given the following input through the keyboard:

Neeraj good

This input will be read correctly and assigned to the character array name. Let us suppose

the input is as follows

255

CU IDOL SELF LEARNING MATERIAL (SLM)

11.5 UNFORMATTED I/O OPERATIONS

Unformatted Input/output is the most basic form of input/output. Unformatted input/output

transfers the internal binary representation of the data directly between memory and the file.

Formatted output converts the internal binary representation of the data to ASCII characters

which are written to the output file. Formatted input reads characters from the input file

andconverts them to internal form. Formatted I/O can be either “Free” format or “Explicit”

format, as described below.

Advantages and Disadvantages of Unformatted I/O

Unformatted input/output is the simplest and most efficient form of input/output. It is

usually the most compact way to store data. Unformatted input/output is the least portable

form of input/output. Unformatted data files can only be moved easily to and from

computers that share the same internal data representation. It should be noted that XDR

(eXternal Data Representation) files, described in Portable Unformatted Input/Output, can

be used to produce portable binary data.

Advantages and Disadvantages of Formatted I/O

Formatted input/output is very portable. It is a simple process to move formatted data files to

various computers, even computers running different operating systems, as long as they all

use the ASCII character set. (ASCII is the American Standard Code for Information

Interchange. It is the character set used by almost all current computers, with the notable

exception of large IBM mainframes.) Formatted files are human readable and can be typed

to the terminal screen or edited with a text editor. However, formatted input/output is more

computationally expensive than unformatted input/ output because of the need to convert

between internal binary data and ASCII text. Formatted data requires more space than

unformatted to represent the same information. Inaccuracies can result when converting data

between text and the internal representation.

11.6 READING/WRITING OF FILES

256

CU IDOL SELF LEARNING MATERIAL (SLM)

To read from a file, first we have to open the specified file in reading mode. If the file

doesn’t exist, then its respective method returns NULL.

The following program shows how to read the contents of a file in C++ −

#include<iostream>

#include<fstream>

#include<string>

usingnamespace std;

int main (){

string readfile;

ifstream myfile ("Tempfile.txt",ios::in);

if(myfile.is_open()){

while( getline (myfile,readfile)){

cout << readfile <<'\n';

}

myfile.close();

}else

cout <<"file doesn't exist";

return0;

}

It will produce the following output −

Writing contents to file

257

CU IDOL SELF LEARNING MATERIAL (SLM)

Note − In this program, we opened a text file in read mode using “ios::in” and then print its

contents on the screen. We have used while loop to read the file contents line by line by

using “getline” method.

The following program shows how to perform the same operation using Erlang. Here, we

will use the read_file(filename) method to read all the contents from the specified file.

-module(helloworld).

-export([start/0]).

start()->

rdfile = file:read_file("Tempfile.txt"),

io:fwrite("~p~n",[rdfile]).

It will produce the following output −

ok, Writing contents to file

Writing into a File

To write contents into a file, we will first need to open the required file. If the specified file

does not exist, then a new file will be created.

Let’s see how to write contents into a file using C++.

Example

#include<iostream>

#include<fstream>

usingnamespace std;

int main (){

ofstream myfile;

258

CU IDOL SELF LEARNING MATERIAL (SLM)

myfile.open ("Tempfile.txt", ios::out);

myfile <<"Writing Contents to file.\n";

cout <<"Data inserted into file";

myfile.close();

return0;

}

Note −

fstream is the stream class used to control file read/write operations.

ofstream is the stream class used to write contents into file.

Let’s see how to write contents into a file using Erlang, which is a

functional programming language.

-module(helloworld).

-export([start/0]).

start()->

{ok,File1}= file:open("Tempfile.txt",[write]),

file:write(File1,"Writting contents to file"),

io:fwrite("Data inserted into file\n").

Note −

To open a file we have to use, open(filename,mode).

Syntax to write contents to file: write(filemode,file_content).

Output − When we run this code “Writing contents to file” will be written into the

259

CU IDOL SELF LEARNING MATERIAL (SLM)

file Tempfile.txt. If the file has any existing content, then it will be overwritten.

11.7SUMMARY

C++ accomplishes input/output operations using concept of stream. A stream is a

series of bytes whose value depends on the variable in which it is stored.

This way, C++ is able to treat all the input and output operations in a uniform

manner.

Thus, whether it is reading from a file or from the keyboard, for a C++ program it is

simply a stream.

A stream is a source of sequence of bytes.

A stream abstracts for input/output devices. It can be tied up with any I/O device and

I/O can be performed in a uniform way.

The C++ iostream library is an object-oriented implementation of this abstraction.

It has a source (producer) of flow of bytes and a sink (consumer) of the bytes.

The required classes for the stream I/O are defined in different library header files.

Streams can also be tied up with data files.

Unformatted input/output is the simplest and most efficient form of input/output.

It is usually the most compact way to store data. Unformatted input/output is the least

portable form of input/output.

Files are used to store data in a storage device permanently. File handling provides a

mechanism to store the output of a program in a file and to perform various

operations on it.

A stream is an abstraction that represents a device on which operations of input and

output are performed. A stream can be represented as a source or destination of

260

CU IDOL SELF LEARNING MATERIAL (SLM)

characters of indefinite length depending on its usage.

ofstream: This Stream class signifies the output file stream and is applied to create

files for writing information to files

ifstream: This Stream class signifies the input file stream and is applied for reading

information from files

fstream: This Stream class can be used for both read and write from/to files.

11.8KEY WORDS/ABBREVIATIONS

C++ iostream Library: The C++ iostream library is an object-oriented

implementation of this abstraction.

Stream: A stream is a series of bytes whose value depends on the variable in

which it is stored.

Unformatted Input/output: Unformatted input/output is the simplest and

most efficient form of input/output.

11.9LEARNINGACTIVITY

1. Write a program to store the information of about 5 students in a file and read the contents

and print them on screen

__________________________________________________________________________

__________________________________________________________________________

2. Write a proper C++ statement with proper arguments that would be called to move the file

pointer back by 2 bytes

__________________________________________________________________________

__________________________________________________________________________

261

CU IDOL SELF LEARNING MATERIAL (SLM)

11.10 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE)

A. Descriptive Types Questions

1 Modify a program that opens a file and counts the whitespace-separated words in

that file.

2 Create a program that counts the occurrence of a particular word in a file (use the

string class’ operator ‘==’ to find the word).

3 Analyze a program to display a file a line at a time, waiting for the user to press the

“Enter” key after each line

4 Create a vector<float> and put 25 floating-point numbers into it using a for loop.

Display the vector.

5 Create a vector and<float> put 25 numbers into it as in the previous exercises. Now

square each number and put the result back into the same location in the vector.

Display the vector before and after the multiplication.

B. Multiple Choice Questions

1. . Which header file is required to use file I/O operations?

(a) <ifstream>

(b) <ostream>

(c) <fstream>

(d) <iostream>

2. Which of the following is used to create an output stream?

(a) ofstream

(b) ifstream

(c) iostream

262

CU IDOL SELF LEARNING MATERIAL (SLM)

(d) fsstream

3. Which of the following is used to create a stream that performs both input and output

operations?

(a) ofstream

(b) ifstream

(c) iostream

(d) fstream

4. Which of the following is not used as a file opening mode?

(a) ios::trunc

(b) ios::binary

(c) ios::in

(d) ios::ate

5. By default, all the files in C++ are opened in _________ mode.

(a) Text

(b) Binary

(c) ISCII

(d) VTC

Answers

1. (c), 2. (a), 3. (d), 4. (a), 5. (a)

11.11REFERENCES

“Programming in C++” by M T Somashekara

“Thinking in C++” by ECKEL

The C++ Draft Standard by the International C++ Standards Committee (2013)

Large-Scale C++ Software Design by John Lakos (1996)

263

CU IDOL SELF LEARNING MATERIAL (SLM)

http://www.cplusplus.com/reference/iostream/

http://www.cplusplus.com/reference/iostream/istream/getline/

https://www.learncpp.com/cpp-tutorial/186-basic-file-io/

https://www.thecrazyprogrammer.com/cpp-programs

Analysis of Various I/O Methods for Large Datasets in C++ Kushaagra Moghe

C++ STREAMS By Mike Toms Overload, 1(1):, April 1993

Bit-Oriented I/O with Templates By Mark Nelson, July 29, 2014