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

Object Oricnted Concepts and Programming/1

UNIT1
0OPS Introduction
1.1 Introduction to Object Oriented Programming

C is a procedural language which is very powerful and mainly used in


cdeveloping of system software like Operating system kernel, compilers
editors etc and is also used for developing application software. But C
language could not model real world problems, because of this advantage
it has led to the development of C++. C++ is an object oriented
programming language developed by Bjarne Stroutsup at AT & T Bell
Laboratories, USA in early 1980's. C++ is an extension of C with concept
of classes and objects. The C++ language has added object oriented
features like classes, objects, inheritance, function overloading, operator
overloading, virtual functions etc. All these features are not available in C
language and these features are so powerful that they help in modeling of
real world problems more effectively, hence, C++ became more popular
choice among programmers for application development.

1.1.1 Procedure Oriented and Object Oriented

1.1.1.1 Procedure Oriented Programming


The concept of Procedure Oriented Programming can be
represented in the figure as follows:a ici
Main Function

Function 1 Function 2

Function 3
Function 4 Function 5
The main features of Procedure Oriented Programming are as
follows:

1. In procedure oriented programming the application


programs are organized, designed and written around the

Visit us at http://www.dotcombooks4u.com
2/OOPS Introduction

procedures making the structured


programming procedur
ure
centricC.

More emphasis is laid on procedures or algorithms rather


than
2
data.

3. Procedure oriented programs supports modular programs


i.e., a larger program performing a task is divided
into
number of modules called procedures or functions.

4 In a procedure oriented programming, data is not secure, as it


is freely moved from one function to another.

5. Every function or procedure in a procedure oriented


programming environment can have access to global data, can
change their values, leaving the resultant code with more
bugs.

6. Compilers implementing procedure oriented program ming


do not prevent unauthorized functions from accessing or
manipulating variables in a programn.

7. Procedure oriented programming is difficult to design,


maintain and enhance the software.

8. Procedure oriented program employs top-down style or


programming.

9 The disadvantage of procedure oriented


programming 1S 15
incapability to model real world problems.

10. Some of the languages


which supports procedure orie
programming are C, Pascal etc.
1.1.1.2 Object Oriented
Programming
The concept of Object Oriented
the figure as follows:
Programming can be representca in

Yisit us at htt
Object Oriented Concepts and Programming/3

Objectl Object 2

Data Data

Functionss Functions

Object 3

Data

Functions

The main features of Object Oriented Programming are as follows:

.
1. In object oriented programming, the application programs are
organized, designed and written around the data making the
object oriented programming data centric.

2. More emphasis is laid on data rather than on procedures or


algorithms

3. A module in object oriented programming paradigm is made


to be a collection óf classes and objects rather than dividing
entire program into many subprograms or functions.

Visit us at http: /www.dotcombooks4u.com


4/0OPS Introduction

4. In an object orienlcd programming, data is tied more closelu


to the functions and does not allow the data to frcely
around
secure. Both
the entire program making the data more
functions and data are treated together as integral entities.

5. Unlike procedure oriented programming data is hidden and


cannot be casily accessed by external functions.

6. Compilers implementing object oriented program ming, and


does not allow unauthorized functions to access the data thus
enabling data security. Only the associated functions can
operate on the data and there is no chance of bugs creeping
into program.

7. Object oriented programming is easy to design, maintain and


enhance the software.

8. The main advantage of Object oriented programming is its


capability to model real world problems.

9. The main added features of Object COriented Programming are


as followS:
12
i)Inheritance
It is a relationship between two classes where one class
i.e, child inherit characteristics of another class ic,
parent.
many
ii) Polymorphism
The meaning of Polymorphism is "having multiple
forms". It is a phenomenon by virtue of which a single
entity can exist in two or more forms. For example,
OOP two functions can have same name with differen
set of arguments, this is known as function overloadin8
which is a kind of polymorphism. 'The other kind o
polymorphism is achieved through virtual functions an
operator overloadin8

Visit us at http:/ www.dotcombooks4u.com


Object Oriented Concepts and Programming/5

iii) Encapsulation
It is a mechanism by which data and functions are
packed together into a single unit called class.
Encapsulation provides data security, i.e., the data inha
particular class is not accessible to the outside world. The
functions that are packed in same class can have direct
access to the data of particular class.

iv)Abstraction
It is an idea of representing necessary details without
including background details which are needed for
presentation. This helps in reducing the complexities im
understanding the unnecessary details, that are really not
so important or needed. Class use the concept of example
of Abstraction.

10. Some of the languages which supports object oriented


programming are C++, Java, Smalltalk etc.

1.1.2 Difference Between C and C++


C++ is called superset of C as C++ extends, Glanguage. The major
retain its compatibility/with C. All
design criterion of C++ was to KeeRP
valid C programs are C++ programs, hence a Ct+ compiler can
compile and execute all C programs but the reverse is not true. The
C++ language uses most ot the reatures or language sucn as
decision-making statements, looping statements, structures. C++
some
supports the keywords of C language and C++ also contains
oriented
additional keywords which helps in implementing object
C and C++ arc as
paradigm. The major differences between
follows:

C C++
is aprocedure orientedC++ is object oriented
C more
programming language where programming where
on data rather
more emphasis is laid on emphasis is laid or
on procedures
procedures or algorithms rather than
|

algorithmns.
than data.

Visit us at http:/lwww.dotcombooks4u.com
6/OOPS Introduction

There is no strict type-checking | Strict type-checking is donein


in C. C++, so many programs that
run well in compiler will
result in errors and warnings
under C++ compiler.
C supports only Early binding, C++ supports both Early
Early
in which all the functions binding and Late binding. Late
related to the function call are binding is a process of of
resolved at compile time. AII | resolving the functions related
individual resolved function | to the function call during run
calls create an individual (.o) time. Here the functions are
files which can be later linked | related to class much after the
together to create a final compilation time. It is also
together
executable file. known as Dynamic binding.
Concept of default arguments Concept of default arguments
are not availableinC languageare available in C++ language.
Functions cannotbe overloaded.| Functionscan be overloaded.
The memory management is The memory management is
done by the built-in functions, | done by operators ncw
malloc, calloc, realloc, free.
and
delete.
Declaration of the variables Declaring of variables can be
have to be done before the first done at any point in the
executable statement within
block making the declaration of
a |program wherever necessary,
making declaration of variables
variables more rigid. more flexible compared to C
language
1.1.3 C++ Output/ Input
The main aim of any programming language is help the user to do
certain operations, which include,
system, using which processor
user giving some input to the
does some operations and gives
back the user the result. Since
user cannot speak the hardwar
language the high level language
communication by the user like C++ is used as a means o
which will be later converted
hardware language during int
the hardware.
compilation process to communicate

Visit us at http://www.dotcombooks4u.com
Object Oriented Concepts and Programming/7

1.1.3.1 Console Output PoinaD


The cout is used to write the characters on to the standard output
stream. The operator "<<", which is a binary operator sends the
contents of the variable on its right to the object on its left. The
operator "<<" is also called as insertion operator. This operator is
actually bitwise left-shift operator but it has been overloaded to
make it work as insertion operator. The advantage of insertion
operator is that it does not require any format specifiers like %d,
%C. %t ete as in C language to
represent the data of different data
typcs.

Example:
cout'x="<<x<<endl;
The above statement tries to write the value of x on the screen or
monitor.

1.1.3.2 Console Inputinsteol of Scan)


The binary operator ">>" is also known as extraction operator
which is used to get the data from the object on its left, i.e., the
standard input stream, and tries to store in the memory location
associated with it using variables towards its right. This operator is
bitwise right-shift operator but it has been overloaded to make it
work as extraction operator.

Example:
cin>>"x;

The above statement waits for the user to enter a value through the
keyboard.

1.1.4 Keywords in C++


Keywords are reserved words whose meaning is already been
defined for a particular language. The keywords cannot be used as
variable names. The keywords that are available in C++ language
can be represented in the table as follows:

Visit us at http://www.dotcombooks4u.com
8/0OPS Introduction

explicit protectcd typeid


asm typename
auto export public 9
extern register union
break
case false reinterpret_cast unsigned
catch float return using
char for short virtual
class friend signed void
const goto sizeof volatile
const_cast if static wchar
while
t
continue inline static cast
default int struct
delete long switch
do main template
dynamic_cast mutable this
else namespace throw
enum new true
operatoor try
private typeder

1.1.5 New style of header file specification


In ANSI Ct+ standárd, a new way to specify header files is
defined. They do not use the old style of h cxtensions to file
names, examples are #include<iostream>, #include<fstrcam> etc.

The old style of header file specification like "iostream.h" ,


"fstream.h" is also supported to maintain backward compatibility.
The new version of header files can be represented in the table as
follows:
Old Version New Version
assert.h> <cassert>
<ctype.hn>
Scctype>
Sfloat.h> <cfloat>
<limits.h> <climits>
Smath.h> Kcmath>
stdio.h> Kcstdio>
<stdlib.h>
Scstdlib>
string,h1> <cstring>
time.h>> Sctima
Object Oriented Concepts and Programming/9

,
1.1.6 Comments in C++
In C language, multiline comments are used. In C, the comments
are enclosed between_* and */. In C++, we have single line
comments starting with symbol two forward slashes i.c., //. Any
comment should be preceded by //. C++ supports both types of
comment styles. The lines that are commented will never be a part
of compliation code.

A sample program which includes comments can be as follows:

Programn
C+ program.with commenis /+This is comment line of C
Supported in C++ also
I/Sample C++ program -This s comment line in C++
#inciudeciostream

:
s Using namespace
int main)
std;
(l endl =n
//Comments helps in documentablity
coute"this is a c++ program"<<endi
return 0;

1.1.7 Variables in C++


A variable is a memory location reserved for use by the program
and is referenced by a specific name. The variables contain values
that can be modified during the program execution. The valucs
rnay be data of different types such as int, float, double etc. Before
1sing the variable, it should be declared by stating the data type of
value that the variable contains. In C, all the variables has: to be
defined at the beginning of scope ie., above all cxecutable
statements, whereas in C++, declaration can be done anywhere in
the scope, i.e., variable can be specified where it has to be used.
While naming a variable, it must be remembered that, the variable
name should not be a keyword and whitespaces are not allowed in
variable name. The variable name may contain a letter, digit and an
underscore(_) character.

Visit us at http: //www.dotcombooks4u.com


10/OOPS Introduction

Program 1.2
#includeciostream.h>
using namespace std;
int main()

int i;
10;
i = "<<i <<endl; Cout ce" i ';
cout<<"i
int j:
j=10;
cout<<"i = "<<j <<endl;
refurn 0:

1.1.8 Reference Variables in C++


A reference variable is an implicit pointer. A reference variable is a
reference or alias for a previously defined variable. The memory
location of the already existing variable is shared by the reference
variable. The reference variable should not be initialized to address
of an object. The syntax for declaring a reference variable is as
follows:

data type> & <reference_variable> = <existing_variable>


Where
data type>> is the type pf data to which the reference variable
is implicitlypointing
&-is known as reference operator
<reference_variable> -> is the new variable which is pointing to the
already exisiting variable and acts as reference
->is known as assignment operator
existing_variable> is the previously defined variable whicn
originally holds the data

Program :

#includeciostream.h>
USing namespace std;
int main()

Visit us at http:
// www.dotcombooks4u.com
Objoct Orienied Concepts and Programming/11

intp 10;
int &r = p:
cOufke"p= "<<p <<'r = <<r < endl;
"

return 0;

1.1.8.1 Features of Reference variable in C++


a. A reference variable must be initialized at the time of
declaration itself.

1 b. Once a reference is made for a variable, it cannot.be made to


2 refer to any other variable.

C. A variable and its reference are bonded strongly, such that a


change in one necessarily results in a change in other.

d. Like int, float and double, the reference variable can also be
made to reference pointer.

e. The major advantage of reference variables is in passing them


as arguments to functions, this have a greater advantage of
ot over passing the address of variables to functions as pointers.

A function can also return by relerence.

:
A reference to an array is allowed in C++.

1.1.9 The bool Data type


It is a new data type added to the C++ language. This datatype has
0.
two values 'true' and "false. 'true' means land 'false' means
'true' and 'false' are keywords in C++.

Program 1.4
y
#include<iostream.h>
U USing namespace std;t .
t 10 int main\|

bool a 25;

Visit us at http://www.dotcombooksdu.com
12/OOPs Introduction

int b = true;
int c false
cout<<"a = "<<a <<end;
cout<<"b = "<<b <<endl;
cout<<"c = "<<c <<endl;
return 0;

function prototyping in C++


1.1.10 Importance of
a declaration statement in the calling
Function prototyping is function's interface to the compiler
program which describes the arguments passed, data typee of
number of
by giving details such as function returns.
arguments, data type of value that
is as follows:
The syntax of function prototyping<argument_list>
returntype> <function_name>
Where function is cxpected to
return_type> is the type of the data the
return to the calling function be a valid
Sfunction_name> is the name of the function and should
identifier
double etc) the
argument_list> contains the type of data (int, float,
definition.
function call passes as arguments to the function
call, the compiler
With function prototyping, during a function
uses the function prototype to ensure that proper
arguments are
compiler
passed and the, return value is handled, and if not,
error
identifies its during compilation time itself and displays the
message, because C++ is strict in type checking.

An example of function prototyping is as follows:


float add(int x, float y);

The above statement tells compiler that add is a function which


passes two parameters, first one being int and second one being
float, and the function add() returns the value.of floating point
type to the calling function.

Visit us at http: // www.doteombooks4u.com


Object Oriented Concepts and Programming/13

The above example can also be written as follows:


float add(int, float);
The argunment name is not required, it just acts as a placcholder for
the values. The compiler mainly looks for the type of arguments
and it does not matter whether the argument name is specilied or
not.

3 Program g
#includeciostream.h>
USing namespace std;
float add (fint, float): // function prototype
int main()

intx =2;
float y = 3.6, z;
z add(x.y);
Cout<<"x= "<<x << "y = "<<y <<"="<<z <<endl;
return 0:

float add(int a, float b) l T


return(a+b);

1.1.11 Function Overloading


In C++ programming, it is allowed to create two or more functions
with the same name but their parameter declarations should be
different. Hence, the functions that share the same name are said to
be overloaded and the process is called as function overloading. It
OOP. It is possible for
is also known as function polymorphism in
the user to create a set of functions with same names but number
and types of parameter list should be different in each function
with the help of function overloading. The correct function to be
invoked is determined by checking the number and type of the
arguments but not on the return type of the function. Hlencea
function prototype is much necessary and it tries to match
function call to the correct function definition.

Visit us at http:// www.dotcombooks4u.com


14/00PS Introduction3ei

The compiler tries to implement BIST MATCHING strategy whil


performing function overloading on functions, and the strategy is
as follows:

a) Looks for the cxact match of a function prototype with thatof


a function call statement.

b) In case an cxact match is unavailable, it tries to look for


nearest exact match, i.e, the compiler will perform integral
data promotions and then match the call statement with the
function prototype.

) If neither of the case works, then it tries to give an error


message.

Rules for Function Overloading


a) Each overloaded function must differ either by number of its
formal parameters, their data types or sequence of the
parameters.

b) The default arguments of the overloaded functions are not


considered as a part of the parameter list by C++ Compiler.

The return type of overloaded functions may or may not be


same.

Programn .

#includeciostream>
USing namespace std;
int addchar); /function profotype
int add(nt, int); //function prototype
float add(int, float): //function prototype
int main()

char c = 'S';
intx1 = 2, x2= 3;
float fl = 2.2;
int d.e:

Visit us at http:// www.dotcombooks4u.com


Objact Oriented Conccpts and Programming/15

d add(c);
e add(x1,x2):
float f3 = add(x2,f1);
cout <<"c = "<<C<<d<<endl;
cOut <XI= "<<Xl<<"x2 = "<<x2<<"e = "<<e<<endi;
cout <<"x2 = "<<x2<<"fl = "<<fl<<"3 = "<<{3<<endl;
return 0;

int add(char cl)

return(c1+1);

int addfint il, int i2)

returnil+i2):

float addfint i, float f)

returni+H;

1.1.12 Default Arguments .

It is a concept of C++ in which a function assigns a default values


for some or all of formal arguments which does not have a
matching argument in the function call, these default values are
called as "default arguments". This allows us to call a function
e1gwithout assigning all its arguments. If no value is passed for any of
the formal arguments when the function is acalled, the default
value specified in the function prototype is passed to the to the
corresponding formal argument and if all arguments are passed
when the function is called then the default value is ignored.

Program
#includeciostream>
Using namespace std;
int i2, int i3 =6); I/i3 is assigned a default value of 6
int addint il,
Visit us at http:// www.dotcombooks4u.com
16/OOPS Introduction

int main(0

int result.a.b;
a = add(10,20);
b=add(10,20,30); i3 = "<<i3<<" a =
"<<a<<end:
i2 = "<<i2<<"
cout <<"il = "<<il<<" = "<<i2<<" 13 "<<i3<<" b="<<b<<end:
cout <<"il = "<<il1<<" i2
retum 0: }
int addint x, int y, int z}
{

returnx +y+7); }

Features of default arguments to more than one


Default arguments can be assigned
a.
argument.
the
arguments can be used to add new paramcters to
b. Default
existing functions.

Defaults arguments can be used to


combine similar functions
into one.

1.1.13 Inline Function


of using functions in programs is to save a memory,
Objective
is likely to be called
space, that becomes appreciable when function'
many times. lf function is called every time, it
takes a lot of extrd
like jumping 0
time in executing a series of instructions for tasks an
stack,
function, saving registers, pushing arguments into the
small,
returning to the calling function. When function is suc
substantial percentage of execution time may be spent in
preprocessu
overheads. One solution given by C is the use macro
feature, but the drawback is that they are not really functions,
error checking does not occur during compilation. But
overcomes this problem by introducing a new feature called in
function. It eliminates the cost of calls to small functions. An in
function is a function that is expanded in line when it is invo
The compiler replaces the function call with the corrcspond
function code.

Visit us at http: // www.dotcombooks4u.com


Object Oriented Concepts and Programming/17

The inline functions are defined as follows:


inline function-header

function-body

Example
inline double cube(double a)

return (a'a"a);

The above inline function can be invoked by statements like


C=cube(3.0);
d=cube(2.5+1.5);
After execution the value of c and d will be 27 and 64.

lt is easy to make the function inline, all that is required is to add


prefix inline to the function definition. All inline functions must be
defined before they are called. The functions are made inline when
they are small enough to be defined in one or two lines.

Some of situations where inline expansions may not work are:


a. For functions returning values, if loop, a switch or a goto
exists

b. For functions not returning values, if a return statement exists.

C. If functions contain static variables.

d. If inline functions are recursive.

1.1.14 Scope Resolution Operator


Like C, C++ is also a block structured programming language.
Blocks and scope can be used: in constructing programs. Same
variable name can be used to have different meanings in different
blocks. The scope of variable extends from the point of its
declaration till the end of the block containing the declaration.
Variable declared inside a block is said to be local to that block./

Visit us at http:// www.dotcombooksdu.com


18/0OPS Introduction

For example, suppose if the


code is as follows:
Scope resolution operator....

int x = 10;

intx= 1;
***

memory locations
Two declarations of x refer to two different
containing different values.

Statements in the one block cannot refer to the variable x


The blocks in C++
declared in the another block, and vice versa, since
are often nested.

For exanple, suppose if the code is as follows:


Scope resolution Operator

= 10; Block 1
intx

intx =1; Block2

Block2 is contained in block1. The declaration in an inner block


cac
hides a declaration of the same variable in an outer block and,
declaration of x causes it to refer to a different data objcct. Withi
the inner block, the variable x will refer to the data object declarc
therein. ln global version of a variable canno
C language
ca
accessed from within the inner block, but in C++ this problem

Visit us at http: / www.dotcombooks4u.com


Object Oricnted Concepts and Programming/19

be resolved by introducing a new operator :: called scope resolution


operator, which is used to uncover a hidden variable.

It takes the form as follows:


: variable-name

The scope resolution operator allows access to global version ot the


variable count and not the local variable count declared in that
block.

The major application of scope resolution operator will be in the


classes where there a problem arises to identify the class to which
member function belongs.

Program
#include <iostream>
int n = 12: // A global variablet
int main

n= 13; // A local variable


int
cout <<:n << "\n':// Print the global variable: 12
:cout<n <<'\n'; // Printthe local variable: 13

12 Classes and Object

1.2.1 Structures in C
Structures in C language provides a method for packing together
data of different types. It is convenient. for handling a group of
logically related data items. The User-defined daa type is used
with a template to define its data properties. Once the structure
type has been defined, it is necessary to create variables of that type
using declarations that are similar to the buit-in type declarations.
Structure can have arrays, pointers or structures as members.

Example:
struct student|
char name|20];

Visit us at http :// www.dotcombooks4u.com


20/0OPS Introduction

int roll number;


float total_marks;

In the above example, the keyword struct declares studcnt as a new


data type that holds three fields of different data types and the
ficlds are known as structure members or elements. The identifier
student is referred to as structure name or structure tag, and it can
be used to create variables of type student,

Example:
struct student A; //C declaration
In the above statement, A is a variable of type student and has
thre
member variables as defined by the template. Member variables
can be accessed using the dot or period operator as:

strcpy(A.name,"ABC");
A.roll_number=1;
A.total_marks=595.5;

Limitations of C Structures
A
a Cdoes not allow the struct data type to be treated
like built-in
types.

Example:
struct complex{
float x
C float y
Struct complex cl, c2, c3;

The complex number


c1, c2, and c3 can easily
values using the dot be assigneu
operator but we cannot
numbers or subtract
one from
add two comple
the other.
For example: c3 = cl1 + c2; is illegal
in C language.

Visit us at
http: // www.dotcombooks4u.com
Object Oriented Concepts and Programming/21

b. C structures do not permit data hiding. Members can be


directly accessed (public members) by the structure variables
by any function anywhere in their scope.

1.2.2 Structure in C++


C++ supports all the features of structures as defined in C. is
It also
expanded to suits its OOP features. It attempts to bring the user-
defined type as close as possible to the built-in data types and also
provides a facility to hide the data which is one of the main feature
of OOP. Inheritance is a mechanism by which one type can inherit
characteristics from other types which is also supported by
* In
C++, a structure can have both variables and functions as members.
It also declare some of its members as private and they cannot be
ccessed directly by the external functions. In C+*, structure names
are stand-alone and can be used like any other type names. The
keyword. struct can be omitted in the declaration of structure
variables.

Example
Declaration student A is valid in C++ but it is not in C language.

C++ incorporates all these extensions in another user-defined type


known as class. 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 data and functions.
1.2.3 Access Specifier
There are 3 access specifiers for a class/struct/Union in C++. These
access specifiers define how the members of the class can be
accessed. Any member of a class is accessible within that
class(Inside any member function of that same class). The three
different types of access specifiers are as follows

Public - The members declared as Public are accessible from


outside the Class through an object of the class.

Protected- The members declared as Protected are accessible from


outside the class but only in a class derived from it.

Visit us at http: // www.dotcombooks4u.com


22/OOPS Introduction
are only accessible from within.the claass,
Private These members
outside the class.
they cannot be accessed

1.2.4 Classes its associated function


is way to bind the data and ns
A class necessaru
to be hidden, if ary
together. It allows data and functions
a class, we creating a new
from external use. When defining any other built-in data
abstract datatype that can be treated like
type.

A class specification has two parts:


a) Class declaration
b)Class function definitions scope of its members
The class declaration describes the type and
the class functions are
The class function definitions describe how
implemented.

The general form of class declaration is as follows:


class class_name
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;

The class declaration is similar to struct. The 'keyword class


is
specifies, an abstract data of type class_name. The body of class
enclosed within braccs and terminated by a semicolon. It contains
the declaration of variables and functions and is collectively called
as class members. It is 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 labelsand arcfollowed by colon(;). Class
members declared as private can be acccssed only from within t
class. On the other hand, public members can be accossed fron
outside the class also. The data-hiding (using private declaration) "

Visit us at http:// www.dotcombooks4u.com


Object Oricented Concepts and Programming/23

the key feature of object-oriented programming. The use of private


keyword is optional. By default, the members of a class are private.
If both the labels are missing, then, by default, all members are
private. And class is completely hidden from outside and does not
serve any purpose. Variables declared inside the class are known as
data members and the functions are known as member functions.
Only the member functions have access to the private data
members and private functions.The public members (both
functions and data) can be accessed from outside the class. The
binding of data and functions together into a single class-type
variable is referred to as encapsulation.

In general, class can be represented in the figure as follows:


CLASS
No cntry to
private area Private Area
X
Data
Functions

Public Area

Entry allowed
Data
to publie area.
Functions

A typical class declaration can be as follows


class item
int number; // variables declaration
float cost;// private by default
public:
void getdata(int a, float b);// functions declaration
void putdata(void); //using prototype
// ends with semicolon

It can be represented in the figure as follows:

Visit us at http:/www.dotcombooks4u.com
24/0OPs Introduction

ITEM
Class: 1TEM
getdata()
DATA
number T
cost putdata()

FUNCTIONS
getdata( )
putdata()

1.2.5 Objects in C++


define any objects of item bu
The declaration of item does not
what they will contain. Once class has been declared
specifies only
using the class name.
we can create variables of that type by

Example
x
item x;// memory for is created.
the-
statement creates a variable x of type item. In C++,
The above
are known as objects. So x is called an object of typc
class variables
allows to declare more than one object in one
item. It also
statement.

Example
item x, y, Z;

of an object is similar to that of variable of an-


The declaration object at this stage
Necessary memory is allocated to an
basic type. not create an~
only a template and
The Class specification provides
space for the objects. Objects can also be created when
memory names immediately after th-
class is defined by placing their
structure.
closing brace, as it is done in the
as follows:
For example, suppose if the code is
classitem
www.dotcombooks4u.com
Visit us at http : //
Object Oriented Concepts and Programming/ 25

x, y, Zj

The above code would create the objects x, y and z of type item. It
is prefer to declare the objects close to the place where they are
used and not at the time of class definition.

1.2.6 Characteristics of Access Specifier


Member access determines if a class member is accessible in an
expression or declaration. For example, suppose if x is a member ot
class A, then class member x can be declared to have one of the
follo wing levels of accessibility:

public: x can be used anywhere without the access restrictions


defined by private or protected.

private: x can be used only by the members and friends of class A.


protected: x can be used only by the members and friends of class
A.
A, and the members and friends of classes derived from class

The members of classes declared with the keyword class are private
keyword
br default and members of, classes declared with the
struct or union are public by default.
use one of the access
To control the access of a class member, you
class membcr
specifiers public, private, or protected as a label in a
list.

Program
struct A {
friend class C;
private:
int a;
public:
ini b;
protected:
int c:

Visit us at http ://www.dotcombooks4u.com


26/OOPS Introduction

siruct BA
void f() {
b=2
C 3;

struct C
void f{A x{
X.a = 4
x.b = 5;
x.C = 6:

:
int main(0 {
A y:
Y.b 8;
BZ,
= 11;
z.b

The access of data members A:a A:b, and A:c in various scopes of
the above examplecan berepresented in the table as follows:
Scope A::a A::b A::c
function No accesSs. Access. Member Access. Class B
.B:f0 Member A::a A::b is public. inheritsfrom A.
15 is private.
function Access. Access. Member Access. Class Cis a
C::0 Class C is a A::b is public. friend of A.
friendof A.
object y No access. Access. Member No access. Member
in Member y.a y.a is public. y.cis protected.
main() is private:
object z No acccss. Access. Member No access. Member
in Member z.a z.a is public. Z.c is protected.
main)L is private.
Visit us at http: // www.dotcombooks4u.com
Object Oriented Concepts and Programming/27

An access specifier specifics the acccssibility of members that


follow it until the next access specificr or until the end of he class
definition. You can usc any number of access specificrs in any
order. If you later define a class member within its class definition,
its access specification must be the same as its declaration. A class
member has the same access control regardiess whether it has been
delined within its class or outside its class.Access control applies lo
names. In particular, if you add access control to a typedef name, it
affects only the typedef name.
1.2.7 Furction outside a class
as
Men ber functions can be defined in two places, they are follows:
a) Outside the class definition
b) Inside the class definition

Whether the member function is inside or outside the class,


pertorm
irrespective of the place of definition, the function should
be identical in
the same task. The code for the function body would
the function
both the cases. There is a subtle difference in the way
header is defined.
class have to be defined
Member functions declared inside a
definitions are like normal
separately outside the class. Their
hcader and function body.
functions and should have the function

support the old version of function definition,


Since C++ does not
prototype form must be used for defining the function
the ANSI
important difference between a member function and a
licader. The
function is: a member fuhction incorporates a membership
normal "Tlabel tells the compiler which
class
header.
identity label' in the
the function belongs to.
a member function definition is as follows:
The general form of function-name (argument declaration){
return-type class-name ::

function body

http://www.dotcombooks4u.com
Visit us at
28/OOPS Introduction

The menmbership label clasS-name:: tells the compjler that the


function function-name belongs to the classname. The scope of
function is restricted to the class-name specified in the header
linc.The symbol : is called the scope resolution operator.

The member functions have some special characteristics that are


often used in the program development.

Several different classes can use the same function name. The
membership label will resolve their scope. Member functions can
access the private data of the class. A non-member function cannot
do so. A member function can call another member function
directly, without using the dot operator.

Example:
void item:: getdata(int a, float b)o N

number=a;
cost= b;

void item:: putdata(void)

cout << "Number=" << number'<< "\n"


cout << "Cost= << cost << "\n";
"

1.2.8 Initialization of variable in C++


When declaring a' regular local variable, its value is by default
concrete
undetermined.. But you may wan t a variable to store a
value at the same moment that it is declared. In order to do that,
in
you can initialize the variable. There are two ways to do this
C++, they are as follows:
an
The first one, known as c-like initializntion, is done by appending
equal sign followed by the value to which the variable will
bDe

initialized:

type identifier = initial_value;

Visit us at http: // www.dotcombooks4u.com


Object Oriented Concepts and Programming/29

For example, if we want to declare an int variable


called n initialized with a value of 0 at the moment in which it is
declared, we could write:

int a = 0;

The otherway to initializc variables, known as consiruclor


initialization, is done by enclosing the initial value between
parentheses ():
type identifier(initialLvaluc);
For example:

int a (0);

Both ways of initializing variables are valid and equivalent in C++,

Programn
I/ initialization of variables
#include ciostream> .

Using namespace std;


intmain0
int a=5; // initial value = 5
int b(2): / initial value 2
int result //initial value undetermined
a = a+ 3: -
result a b;
COut << result;
return 0;

1.2.9 Arrow Operator


The arrow operator, -> (that's a minus sign followed immediately
by a greater than), dereferences a pointer to select a ficld. It is
common to dynamically allocate structure variables, so this
operator is commonly used.

Example

Visit us at http:// www.dotcombooks4u.com


30/OOPS Introduction

struct point

int x;
int y;

point "p
p new point;
p->x 12;
p->y = 34;

1.2.10 'this' pointer


The this pointer is a special pointer which is built-in pointer. C++
uses a unique keyword called this tò represent an object that
invokes a member function. It stores the address of current object in
context. The current object can be referred using this pointer any
where in the class. "this" is a pointer that points to the object for
which this function is called, The this pointer can be used only
inside the class, i.e. only inside the member function of the class
and cannot be used outside the the class. The this pointer is a
constant pointer. The unique pointer is automatically passed to a
member function when it is called. The pointer this acts as an
implicit argument to all the member functions.

For an object say, class demo, type of this will be demo* const this.

For a n object of say class temp, type of this will be temp*const this.

When non-static. member's function is called for an object, the


address of the object is passed as hidden argument to the function.

For example: suppose the function call is as follows:


mydate.setmonth(3;
Can be interpreted as
setmonth(&mydate, 3);

Features of this pointer


a) It is an implicit pointer used by the system
b) It stores the address of the current object in reference

Visit us at http:// www.dotcombooks4u.com


Object Oriented Concepts and Programming/31

c)It is constant pointer to an object


The object pointed to by the 'this' pointer can be dereferenced
and modified.
can only be used within non-static functions of the class.
cIt
The this pointer is non-modifiable, assignment to this are not
allowed.

Program
#include <iostream>
Using namespace std;
class MyClass
int data
public:
MyClass() {daia=100:); rdija thga
void Printi ();
void Print2():

/Not using this pointer


void MyClas:Print1(0{
cout data << endl;

l/Using this pointer


void MyClass:Print2() {
cout << "My address ="<< this << endl;
cout <this->data<<endl;
int main()
i

MyClass a;
a.Printl():
a.Print2():

I/ Size of doesn't include this pointer


cout << sizeof(a) << endl;
OUTPUT:
100
My address = 0012FF88
Visit us at http:/ www.dotcombooks4u.com
32/0OPS Introduction

100
4

1.3 Exercise
A. Long Answer Questions
1. Explain about Procedure Oriented Programming.
2 Explain about Object Oriented Programming8
3. Differentiate between Procedure Oriented Programming and
Object Oriented Programming.
4. Explain about Reference Variables with an example.
5. Explain about bool data type with an example.
6. Explain about Function Overloading with an example.
7. Explain about Function Overloading with default parameters
with an example.
8. Explain about Inline Function with an example.
9. Explain about Scope Resolution Operator with an example.
10. Explain about access specifiers and their characteristics.
11. Explain about Classes in C++.
12. Explain about Objects in C++.
13. How functions can be defined and accessed outside a class?
14. Explain about Arrow Operator with an example.
15. Explain about 'this' pointer with an example.
16. Write a C++ program to implement
the usage of reference
variables.
17. Write a C++ program to calculate area of rectangle, triangle
circle using Function Overloading.
18. Write a C++ program using Function Overloading with
default parameters.
19. Write a C++ program to implement the usage of Scop
resolution operator.
20. Write a C++ program to implement the usage of
this pointe

Visit us at http:// www.dotcombooks4u.com


Object Oriented Concepts and Programming/33

21. Write a C++ program to create a student class with data


members as rollno, name, marks of 5 subjects, calculate total
with appropriate member functions and display the result.

B. SHORT ANSWER QUESTIONS,


1. What is class?
2. What is an object?JA2 NESAFde
3. Define Encapsulation.
4. Define Abstraction.
5. Define Function Overloading
?irsia
6. What is an inline function?
7. What is the use of scope resolution operator?
8. What is an access specifier?
9. What is private access specifier ?
10.What is public access specitier?
da
11. What is protected access specifier ?amo
12. What is the use of this pointer ? io a/
13.For what purpose, the arrow operator is used ?
rtud 14. What is Polymorphism? stii 3ri
15. What is a data member and member function?

C. MULTIPLE CHOICE QUESTIONS


1.The operator is used to access global
variable even if the local variable has same name as global
variable.
e a) scope resolution b) logical c) ternary d) arrow

2. Which of the following is not a keyword.


a) bool b) protected c) thin d) for

Visit us at http://www.dotcombooks4u.comm
34/0or Introduction

3. Which of the following keyword is uscd to control to access


a class member.
a) default b) break c) protected d) goto

4. Which of the following statements is truc in C++


a) class members are public by delault
b) classes cannot have data as public members
c) structures cannot have members as functions
d) none of these

5. The words which has predefined meaning and cannot


changed by the user is known as
a) constants b) identifiers c) keywords d) none

D. FILL IN THE BLANKS


1. Procedural oriented language gives emphasis on.
2. are basic runtime entities.
3. allows creation of new classes from old class

4. The object with attributes and mcthods are grouped together


to form a
5. An object is an - 2of class.

6. isthe mechanism in which we ca


define multiple functions with the same name but differe
types of arguments.
7. functions allow everytimne when
called, at each place the actual code from tk
function is
function.
function would be inserted, instead of jump to the
pointer is a variable which is uscd to acces
8. Thee
the address of the class itself.

Visit us at http :// www.dotcombooks4u.com


t t t t Object Oricnted Concepts and Programming/ 35

E. State TRUE or FALSE


1In procedural orientcd language, all data is shared by all
functions. 7

2. Wrapping of data of different types into a single unit is called


as Encapsulation.
3. Polymorphism is cxtensively used in implementing

inheritance.
4. We can create one or more objects of same class type.
5. By default, members of structure are public and that of class

are privatc.
6. A variable can be tied with several references.

7.Using inline functions may reduce execution time, but may

increase program size.


otdo}rligreoa hlov
t giiuoridioiYe: bi

H39AH2 ibn

://www.dotcombooks4u.com
Visit us at http
Management, Co1struco
36/Morc on ++ Classes and Object, Dynamic Memory
Menory
Memory
UNIT 2
Object,
ynamic
Dynan
More on ++Classes and
Management, Constructor & Destructor
class.
another
2.1 More on Classes and Objects menmber variablee of
or a
to have a Class as a
lt is possible

Program
Header File: shape.h
#ifndef_SHAPE_H
#define SHAPE_H
class FRectangle
Length(l), Width(w)
public double w= 0]:
Kectanglefdoublel 0,

lgt)
void setlength(doublewdt):
void setWidth double
const:
double getLengthf)const
double getWidth() const:
double Perimeter()
double Areal| const
void Properties()

private:
double Length;
double Width:

#endif //_SHAPE_H

Source File: shape.cpp

#include <iostream.h>
#include "shape.h"
Visit us at http:// www.dotcombooks4u.com
eObject Oricnted Concepts and Programming/37
void FRectanglesetLength|double
Igt
Length= lgt:

void FRectangle::setWidth(double
wdt)
Width = wdt;

double FRectangle::getLength() const


i21e G
return Length;
.
double FRectangle::getWidth() const

return Width;

double FRectangle:Perimeter() const

return 2 (Length + Width):

double FRectangle::Area(} const

return Length* Width:

void FRectangle:Properlies()

cout "nRectangle characteristics";


cout < "\n\iLength ="<< Length;
cout < "\n\tWidth ="<Width;
cout << "\n\iPerimeter = "<< Perimeter():
Cout <"\n\tArea="<<Area() << endl

Header File: brick.h


Visit us at http://www.dotcombooks4u.com
&Destructor
38/More on ++Classes and Object, Dynamic Memory Management, ONstructor
Coiistre

#ifndef BRICK H
#define BRICK_H_

#include "shape.h"
class Brick

public:
Brick()
void setThickness(double Tck);
VoId setDimensions(double l, double w, double i
void setColor(char clr);
void settexture(char ixr);
char getColor() const,
char getTexture() const;
double olumel) const;
void Display():
private:
FReciangle shape
char Color:
char Texture;
double Thickness; one} muts

BRICK_HL
tendif //
Source File: brick.cpPP
#include ciostream.h>
i#include "brick.h"

void Brick:seThickness|double Tck)

Thickness = Tck;

void Brick::setColor(char clr)ee4

Color clr;
Visit us at http:// www.dotcombooks4u.com
Object Orienled Conccpts and Programming/39

void Brick:setTexture(char txr

Toxlure= txr;

void Brick:seiDimensions(double l, double w, double 1)

shape.setLengih ();
shape.setWidth(w);
sellhickness(1:

char Brick:getcolor() const


relurn Color;

char Brick::gettexturel) const


return Texture:
.
double Brick::Volumel) const

return shape.getlength() * shape.getWidth() Thickness;

void Brick::Display()

COut <"\nBrick characteristics"; * dr


ot, iiszigy
cout < "\n\fLength ="< shape.getlength(): ! a 3ytisy
cout < "\n\tWidth ="<<shape.getWidth{);
cout << "\n\tArea «shape.Areol
Cout < n\tVolume" <<Volume()
cout "\n\tColor ="« getColor();
<
COut "\n\{Textture ="<< gettexture():
cOut << endl;
pte 23UIDT

Visit us at http:// www.dotcombooks4u.com


Destructor
Constructor &
40/More ou ++ Classes and Object, Managenment,
Dynamic Memory Manng

Main File: Exo.cpp

#include"shape.h"
#include "brick.h"

VOId mdin{) ob w b Ioicuec:


Brick brick;

brick.setDimensions(12.50, 8.75, 5.55):


brick.setColor 'Bone White"):
brick.setTexure("Early Breeze");

brick.Displayl:

files, namely, shape.h, brick.h,


two header
ne above program contains
exo.cpp. The shape.h contains the brick.h contains
Snape.cpP, brick.cpp, class, brick.cpp and shape.cpp
the function prototype of brick and shape
brick and shape class, exo.cpp is the main
Contains the operations of
object (the shape class implements a rectangle)
program using which one
called as a member variable of another object (a brickk).
can be

Accessor functions functions. 1his is


accessor function in C++ is like the getter and setter
An public and changing it
making a class member variable
used instead of not directly accessible. To
object, It is made private and
directly within an
accessor function must be callcd.
read or modify the object member, an
a getLevel() would return
Typically for a member such as Level, function
to assign it a value. It is possible to
the value of Level and setLevel() is
access private data through accessor functions.
A
Program
#include ciostream>
#include <cstring>

Visit us at http:// www.dotcombooks4u.com


Object Oricnted Concepts and Programming/ *1

Using namespace std:

class Shape{
double width;
double heighi;
public:

void display() {

COut"Width and height are "<<width <<" and "<< height <
"\n;

/ accessor functions
double getWidth(){return width; }
double gatHeight{} {return height;}
void setWidth{double w) { width = w; }h erii phia
void setHeight[double h} { height = h:}

class Tricingle:public Shape {iuiiei sfeieitoi


public:
char style[20];

double area() {

returngeiWidth()"getHeight()/2det sr

void st.owStyle{) {
Out << "Triangle is"<< style <<"\n";

Triangle
fl
Triangle 12:
t1.setWidth(4.0):
t1.setHeight(4.0):
strcpy(t1.style, "isosceles); vets, ris
t2.setWidth(8.0);
12.selHeight(12.0);
Visit us at http://www.dotcombooks4u.com
CousiruclU.
1nnageunent,
++ Classes and Object, Dynamic Memory Manns
42/Mor on

strcpy(12.stylo, "right"):
11.showStyle();
11.display():
cout << "Arca is "<< 11.areal) << "\n:
12.showStyle();
12.display):
coul << "Area is << 12.area() <<"\n;
"

return 0:

2.1.1 Member Functions and Data Members

Member Functions
in two placcs, they are
defined
Mcmber functions can be
a) Outside the class definition
b) Inside the class definition
inside a class have to be detincd
Mcmber functions declarcd Their dcfinitions are like normal
SCparately outside the class. have the function hcader
should
functions. The member functions support the old version of
C++ does not
and function body. Since for
definition, the ANSI prototype form must be used
function
defining the function header.

The difference bctween a member


function and a normal function
member function incorporates a membership "identity
is that a
compilcr which class the
label in the header and the 'labcl tells the
function belongs to.

Defining Member functions - Outside the class


The general form of a member function definition is as follows:
return-type class-name:: function-name (argument declaration)

function body 1

92.
In the above syntax, the membership label class-name tells the
compiler that the function function-name belongs to the classnamc.

Visit us at http:// www.dotcombooks4u.com


Rat Object Oriented Concep and Programming/ 43

The scope of the function is restricted to the class-name specilicd in


the header line.

The symbol : is called the scope resolution operator.

The characteristics of member functions are as follows:

a. Several different classes can use the same function name. Ihe
'membership label' will resolvc their scope
A
b. Member functions can access the private data of the class.
non-member function cannot do so.

C. A member function can call another member function directly,


without using the dot operator.

Programn -*

#include<iostream>
Using namespace std;
class item
ptrijiobieg:1e
r
void getdatafint a, float b): 2
void putdata(void); }:
b}
void item : getdatafini a, float

number=a;
cost = b; T
void item:: putdata(void)
<<
<< number "\n
" fU,
cOut << "Number=
= << cost << "\n":
" }
cout <"Cost
int main(

i.temilil.getdata|5,12.5);
1.putdatal); els nos a
www.dotcombooks4u.com
Visit us at http://
Destructor
Constuctor &
44/ Morr on t+ gement, Co"
Classrs and Object, Dynamic Memory Mamgement,

replace the
Defining Member functions clas to
Inside the function is inside the
One more method of defining a member definition
definitionted as an
an
function trcated
cd
function declaration by the actual class, it is apply to an
class. When a function is defined inside a aPPy
limitations thatfunctions are
inline function. The restrictions and small funce
inline functions are also applicable here.
defined inside the class definition.

Program
class item
int number;
fioat cost:
public:
void getdata(int a, float bl: //declaration
// inline function the ciass
void putdata/void) { // definition inside
Cout << "Number = "<< numbeer
cout << "Cost = "<<cost;

void item::getdatalint a, float b)


numberra;
cost= b; v]olobiugbiov

int main

item il
il.getdata(5,12.5]
il.putdatal}:

Private Member Functions


It is a normal practice to place all the data items in a private section
and all the functions in public. Some situations require to have
functions to be hidden from the outside calls. Tasks such as
deleting account in a customer file, or providing increment to an
employee are events of serious consequences and the functions
Visit us at http://www.dotcombooks4u.com
atsast taObJect Orlented Conceptn and Proyranming/45
handling such tasks slhould have restricled
access, It is posible
using privale member function fcature. A
private member function
can only callecd by another function that
is member of its class,
not possibde to access privale function It is
by an object using, the
operator. dot

Example
class sample{
int m;
void read(void);
public:
// privale member function
void update (void);

- Lets sl be a object of class sample,


then s1.read() is illegal since
read is private member function
to class sample. The function
read() can be called by the function
update() as:
void sample:: update(void) {
read(); // simple call; no object used.

Data Members
Data members include members that are declared
with any of the
fundamental types, as well as other types, including
pointer,
reference, array types, bit fields, and user-defined types. You
can
declare a data member the same way as a variable, except
that
explicit initializers are not allowed inside the class definition.
However, a const static data member of integral or enumeration
type may have an explicit initializer.

I an array is declared as a nonstatic class member, you must


specify all of the dimensions of the array.

A class can have members that are of a class type or are pointers or
references to a class type. Members that are of a class type must be
of a class type that has been previously declared. An incomplete
class type can be used in a member declaration as long as the size
of the class is not needed. For example, a member can be declared
that is a pointer to an incomplete class type.

Visit us at http: // www.dotcombooks4u.com


Cousimcior & Di

Management,Rcment,
46/Morr on ++ Clnsses and Olject, Dynamic Memory contain
it canMember
type X, but X.
is of cls of return type
of ty
A class X cannot have a member that is
ereces to hat
static
pointers to X, references to X, and type *
a
functions of X can take arguments of
of X.

Example
class X

X *xptr;
X &xref;
static X xcount;
X xfunc(X;

the clasSs.
2.1.2 Friend Functions accessed from outside
members cannot be the private data of
ne private
Non-member function cannot have an access
requires
to
to share a particular
two classes
a class. In some situation,
function.
classes manger and scientist
are two
Example : Suppose if therefunction income tax(0 to.operate on
the
which would like to use
a
handles this case by allowing the
classes. C++ classes, allowing
objects of both these friendly with both
common function to be made private data of these classes. Such a
access to
the function to have of any of these classes.
be a member
function need not
function "friendly" to a class, simply declare
To make an outside
this function as a friend of
the class as follows: il "
class ABC{
public:
friend void xyz(void) // declaration b st

Visit us at http: // www.dotcombooks4u.com


Object Oricnted Concepts and Programming/**

The function declaration should be


preceded by the keyword
friend. Function is defined elsewhere in the program like normar
C++ function.

Characteristics of Friend Functions


a. t is not in the scope of the class to which it has been declared
as friend, since it is not in the scope of the class, it cannot be
called using the object of that class.

b.It can be invoked like a normal function without the help ot


any object. Unlike member functions, it cannot access the
member names directly and has to use an objcct name and dot
membership operator with each member name.

C. It can be declared either in the public or the private part of a


class without affecting its meaning.

d. It has the objects as arguments.

When member functions of one class can be friend functions of


another class. In such cases they are defined using the scope
resolution operator.

Example:
class x {

int fun1(0:// member function of x eaplont

class y{
friend intx:: fun1(); // fun1 of x is friend of y.

In the above cxample, the function fun1) is. a member of class x


and friend of class y.

It is also possible to declare all the member functions of one class as


the friend functions of another class.

Visit us at http:// www.dotcombooks4u.com


Memory Management, Cos specified as
48/More on ++ Classes and Object, Dynamic
it
it ca be
can
If the class is called a friend class, then
follows:

class z of
friend class x; // all member functions
7/ x are friends of z es of
copies
local
crence. Here address of the
A friend function can
be called by to the on the actual
Instead, pointer rks
works
the objects are not made.
called function directly
the values of the
object is passed and the used to alter private
vate members
call. Method can values of
object used in the th
Altering
private members of a class.
principles of data hiding
is against the basic

Programn
#include <iostream.h>
Using namespace std;
class myclass

int a, b;
public: x):
friend int sum(myclass
j):
void set abfnt int
i,

i, int j)
void myclass:set abfint

a =i:b=
int sum(myclass x)
{
return x.a t x.b;

int main|

myclass n;
n.set ab(3, 4);
Visit us at http:// www.dotcombooks4u.com
49
h39,at 4aiObject Oriented Concepts and Programming/

cout < sum{n)}:


return 0;

2.1.3 Friend Class


It is also possible to make an cntire class a friend of another class.
This gives all of the membcrs of the friend class access to the
private members of the other class.

Program
#include<iostream>
Using namespace std;
class Storage

private:
int m_nvalue;
double m_dValue:
public:
Storageint nValue, double dValue)
m_nValue = nValue;
m_dValue = dValue;

sfriend class Display;


class Display

private:
bool m_bDisplaylntFirst;

public: m_bDisplaylntFirst=
Display(bool bDisplayintFirst) {
bDispiaylntFirst:}

void Displayltem(Storage &cstorage)

if (m_bDisplaylntFirst)
cOut << CStorage.m_nValue <<""<
CStorage.m_dValue << end
Visit us at http: www.dotcombooks4u.com
/
50/More on ++ Classes and Object, Dynamic Memory Management, Constrier

else// display double first


cout << cStorage.m_dValue <<""<<
cStorage.m_nValue << endl;

int main()

Storage cStorage(5,6.7);
Display cDisplay(false);
cDisplay.Displayltem(cStorage};
return 0:
Display's
ny of
any
Because the Display class is a friend of can access the pfriend
Storage, private
members that use a Storage class bject though Display is a
even of
members of Storage directily. First, access to the *this pointer
Display has no direct friend of Storage, that
Oge objects. Second, because Displav is a
you want two
torage If
aoes not mean Storage is also
Classes to be friends of each
a friend of
other.
Display.
both must
friend of B, and
B
declare
is a
the
friend of ,
other as a
that
friend. Finally, if class A is a C. When using friend functions-and
does not mean A is a friend of friend function or class to
VIolate
classes, because it allows the class change, the details of the
encapsulation. If the details of the Consequently, limit your use of
friend will also be forced to change.
minimum.
friend functions and classes to a

2.1.4 Array of Class Object type including struct. Similarly, it i


An array can be of any data
arrays of variables that are of the type class
also possible to have
objects.
Such variables are called arrays of

Example
class employeef
char name[30];
float age
public:
void getdata(void);
void putdata(void);

Visit us at http:// www.dotcombooks4u.com


UTE
e n Object Oriented Concepts and Prospsing/51
and ProsfiaTTCS2
KICS
KALOL(NGE
O.
In the above example, the identifieremployce is a user-defincartt
to diTe
type and can be used to creatc objccts, relating
categories of the cmployecs as follows:

employee manager[3]; // array of manager |fa


employee foreman[15]; // array of foreman
employee worker|75];// array of worker ot
An array of objects behaves like any other
array, use the usual
methods to accass individual elements, and then
array accessing
functions
the dot-nmember operator to access the member

Example
manageri-getdata(0
memory the same way as a
An array object is stored in. the
of object is
multidinmensional array. Only the space for data items by all the
spearately and used
created. Member functions are stored
objects.
class object will be as follows:
Inside the memory, the array of
s

name manager[
age

name managerl]

rage
manager 2
name

age

Programn
A
#include <iostream.n> h; rI
class cl{
int i;

public:
http://www.dotcombooks4u.com
Visit us at
ctor
& Dest
52/More on ++ Classes and Object, Dynamic Memory Managcmcnt, Constructor

clint i){i=j:)// constructor


int get_il) { return i)

int main(

clrscr()
cl ob[3] = {1, 2, 3): // initializers
int i
for(i=0: i<3; i++)
cout ob[ü.get i) <<"\n":
return 0;

2.1.5 Passing Class Objects to Function argurnentg


Like any other data type, an object is used as a function
it can be done in two ways, they are as follows:
a. A copy of the entire object is passed to the function
object
In this method, it uses pass-by-value. Since copy of the
te is passed to the function, any changes made to the object
inside the function do not affect the object used to call the
function.

b. Only the address of the object is transferred to the function.


In this method, it uses pass-by-reference. When an address of
the object is passed, the called function works directly on the
actual object used in the call. Any changes made to the object
inside the function will reflect in the actual object. The pass, by
reference is more efficient since it requires to pass only the
address of the object and not the entire object. An object can
also be passed as an argument to a nonmember function. Such
functions have access to the public member functions only
through the objects passed as arguments to it and it cannot
have access to the private data members.

2.1.6 Returning Objects from Functions


A function cannot only receive objects as
arguments but also can
return them.

Visit us at http:// www.dotcombooks4u.com


s tObject Oricnted Concepts and Programming/53

Program
closs refurnObjecl{
int p;
public:
returnObject manipulate|returnObject ro)

ro.p100:

void display () {
cout «< p:}}
int main()

returnObject rol, ro2, ro3;


ro2=rol.manipulatelro3);
ro2.display(

2.1.7 Nested Classes


A nested class is declared within the scope of another class. The
name of a nested class is local to its enclosing class. Unless you use
explicit pointers, references, or object names, declarations in a
nested class can only use visible constructs, including type names,
static members, and enumerators from the enclosing class and
global variables, Member functions of a nested class follow regular
access rules and have no special access privileges to members of
their enclosing classes. Member functions of the enclosing clas
have no special access to members of a nested class.

2.1.8 Namespaces
Namespaces allow to group entities like classes, objects and
functions under a name. This way the global scope can be divided
in "sub-scopes", each one with its own name.
The format of namespaces is as follows: om,lni
Namespace identifier

Entities

Visit us at http:/www.dotcombooksdu.com
&Destrucro
Management, Constructor
54/More on ++ Classes and Object, Dynamic Memory of
the sctthe
and entities
Where identifier is any valid identifierare
is in
within
included
classes, objects and functions that
namespace.

Examplee
namespace myNamespace

int a, b;
variables declarcd
case, the variables a and b are normal access these
th
In this In order to have to
within a namespace called myNamesp
myNamespace
namespa previous
variables from outside the access the
mple, to
use the scope operator :. For we can write:
variables from outside myNamespace
name from a namespacc
keyword using is used to introduce a
Ihe
into the current declarative region

1Program
LAA// namespace exampie
Using .
finclude <iostream>
Using namespace std;
námespace first
intx= 5;
namespace second
0

a93IU
S
AE
*Idouble x = 3.1416;
1512001 E 3rz2i9 i 52
int main ()
Using namespace first;
cOut <<x << endl;

USing namespace second;


cout << X << endl;
Visit' us at http:// www.dotcombooks4u.com
Object Oricnted Concepts
and Programming/55

return 0;

All the files in the C++ standard library


declare all of its entitics
within the std namespace. That is why
wc have generally included
the using namespace std; statement in all
programs that used any
entity detined in iostream.

Dynamic Memory Managemen


2.2.1 Introduction
The Operators new and delete are exclusive of C++ and they are
not available in the C language. Dynamic memory management
can be pOssible using two operators, they are new and delete in
C++.

22.2 Dynamic Memory Allocation using "new"


In order
order to .request dynamic memory we use the the
operator new. "new" is followed by a data type specifier and if a
sequence of more than one element is required then the number of
these will be within brackets [. It returns a pointer to the beginning
of the new block of memory allocated.

Its form is as follows:


pointer=new type
pointer= new type fnumber of_clements]

The first expression "pointer=new type": is. used to allocate


memory to contain one single element of type type. The 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.
Example
int hobby;
hobby= new int [5|

Visit.us.at http://www.dotcombooks4u.com
estruclor
S6/ More on ++ Classes and Olject, Dynamic Memory Management, Coustructor & Dest
elementsS
In this case, the system dynamically assigns space tor five e
for five he
of type int and rcturns a pointer to the first element
o
points
sequence,which is assigncd to hobby. Therefore, now, hobp int.
to a valid block of memory with space for five clements or
assigning
The difference between declaring a normal array anas
y and to
array
to be a
dynamic memory to a pointer is that the size of an at the
constant value, which limits its size to what we dec hercas whercas
moment of designing the program, before its exccution memory during
during
the dynamic memory allocation allows us to assign var. or
any by our
the exccution of the program (runtime) using requested by
constant value as its size. The dynamic memory nory rcque
memory heap.
program is allocated by the system from the
Program
#include <iostream.h>
USing namespace std;
int main)

int "p;
P new int: // allocate space for an int
p 100;
cout << "At" << p <<"";
cOut << "is the value"<< "p<< "\n"
delete p:
return 0

2.2.3 o
Dynamic Memory Deallocation memory is usually limited to
Since the necessity of dynamic
moments within a program, once it is no longer necded it
specific
freed so that the memory becomes available again for
should be
requests of dynamic memory, and it can be done with the
other
help of delete operator.

Its format is as follows:


delete pointer;
delete pointer;

Visit us at http:// www.dotcombooks4u.com


Object Oricnted Concepts and Programming/

The first expression should be used to delete memory allocatcd tor


a single element, and the sccond one for memory allocated for
arrays of elements. The valuc passed as argument to delete must be
either a pointer to a memory block previously allocated with new,
or a null pointer.

Program
#include siostream.h>
Jsing namespace std;
ind main(
clrscr()
int "p;
p new int (87): // initialize to 87
cOut <<"At" << p <<"";
cout <<"is the value "<<*p <<"\n";riWai1
delete p
return 0;

b
2.2.4 "Set_New_Handler" Function
The format of function is as follows:
ncw_handler set_new_handler (new_handler new p) throw()0

In the above function, set new handler keyword sets new_p as


the new handler function.
new .
handler function is the function' that is called by
functions operator new or operator newl when they are not
successful in an attempt to allocate memory. The newv
handler function can make more storage available for a new
attempt to allocate the storage. If, and only if, the function succeeds
in making more storage avaible, it may return.

Otherwise it shall either throw a bad_allocexception (or a derived


class) or terminate the program with cstdlib's abort or exit
functions.lf the new handler function returns (i.e., it made more
storage available), it can be called again if the operator

Visit us at http:/ www.dotcombaoks4u.com


ctor
Memory Management, Constrictor GDES"
on ++Ciasses and Object, Dynamic
*7Nor attempting to
again not successful allocao
newor opcrator new|] function
is
repcat itself until either the
1his may
alocate the storage.handler function fails.
issuccessful or the

Program
#include <iostream>
#include <cstdlib>
#include <newV> std;
Using namespace
void no_memory1to(){allocate memory!\n;
COut << "Failed
exit (1);
() {
int main
new_handler(no_memory); GiB..."
set to allocate
"Atfempting[10241024*1024]:
1

cOut <
char p= new char
cout << "Ok\n":
deletellp:
retun 0:}

2.3 Constructor and Destructor

2.3.1 Constructor mnember function called the constructor


C++ provides a
special
itself when it is created. It is
enables an object to initialize class name. The
which as the
because its name is the same associated class is
special an object of its
constructor is invoked wheneverbecause it constructs the values of
constructor
created. It is called
data members of the class.
declared and defined as follows:
A constructor is
class integer

int m, n;
public:
integer(void);// constructor is calledisits ssrale
Visit us at http://www.dotcombooks4u.com
Object Oricnted Conccpts and Programming/ 59

integer integer (void) | // constructor is defined


m=0;
n-0;

When class contains a constructor, it guarantces that an oDjc


created by the class will initialized automatically.

Example
Suppose if the declaration is integer intl;
Tt not only creates the object
intl of type integer but also initializes
its aata members m and n to zero. There is no need to write any
staterient to invoke the constructor function (as with normal
function). If a 'normal' member function is defined for zeroo
initialization, it is necessary to invoke this function for each of the
objecis separately. It would be inconvenient if there are a large
number of objects.

Program
#include <iostream.h>
#define SIZE 100
// This creates the class stack.
class stack {
int stck[SIZE];
int tos:
public:
stack(); // constrUctor 3iU .o
stack();// destructor
void push(int i):

intpopl)
/stack's constructor functic a
siack:stack{)

tos = 0:
cout << "Stack Initialized\n":
}

I/ stack's destructor function


stack::-stack{)

Visit us at http:// www.dotcombuoks4u.com


Destructo

Dynamic Memory Management, Constuctor


60/Morr on 44 Classes and Object,

cout"Stack Destroyed\n":

i)
void stack::push(int

if(tos==SIZE) {

cout << "Stock is full.\n:


return:

stcktos]=i;
tos+4

int stack::pop(

if(tos==0)
cout <<"Stack underflow.\n":
return 0:

fos
return stck[tos];

int main(0

two stack objects


stack a, b:// create
a.push(1)
b.push(2);
a.push(3):
b.push(4);
cout < a.pop(<< "";
cOut <<.pop<<"*
coul < b.pop|| << "";
cout < b.pop() << "\n;oaudluiial opt2 o
return 0:

Visit us at http:// www.dolcombooks4u.com


ie Object Oriented oncepts and Programming/61

2.3.2 Characteristics
of Constructor
a. It should be declared in
the public section.
b. It is invoked automatically
when the objects are created

C. t do not have return types, not even void and therefore, they
cannot return values.

d. It cannot be inherited, though a derived class can


call the base
class constructor.

e. Like other C++ functions, they can have default arguments.

f. Constructors cannot be virtual.

8 It is not possible to refer their addresses.

h. An object with a constructor (or destructor) cannot be used as


a member of a union.

Constructors make 'implicit calls' to the operators new and


á delete when memory allocation is required.
2.3.3 Types of Constructor
Various types of constructors that are available in C++ are as
follows:

Default Constructor
A constructor accepting no parameters is called the default
constructor.

The default constructor for class A is A: A0. If no such


constructor is defined, then the compiler supplies a default
constructor. The statement A a; invokes the default
constructor of the compiler to create the object a. Whena
Visit. us at http:/www.dolcombooks4u.com
Memory Management, Constructor &Ta
on ++ ClRses and Objrct, Dynamic class
62/Mor
initialization of th
constructor is declarcd lor a class,
objects becomes mandatory.
the
the
of all
b) Parameterized Constructors mbers alize the
the data
Constructor integcr(), initializes necessay:(forent valus valucs
it may different
objects to zero. In practice objects with bjective
objcctive
of different this
various data elements permils to
achieve henen the
when
C++ functionrguments
when they are created. constructor arguuments
to the
by passing arguments constructors that can take tare a
objects are created. The
are called
parameterized constructor.
constructor can be modificd as follows:
The
{
class integer
int m, n;
public: y);//paramcterized constructor
integer(int x, int

integer: integer(int x, int y)l


m=x; ny

constructor, the object declaration


parameterized
In case of
like: integer int1; will
not work.
to pass the initial valucs
requires
Parameterized constructors function when an object is
constructor
as arguments to the
two ways:
declared, it can be done in
explicitly
By calling the constructor
implicitly
By calling the constructor

can be as follows:
The explicit declaration
integer intl = integer (0, 100);

shorthand method and is


The implicit way sometimes called
used often as easy to implement and will be shown as:

Visit us at http:// www.dotcombooks4u.com


Object Orient ncepts and Programming/6
integer int1(0,100);

It is also possible
to define constructor functions as inline
functions.

Example
class integer{rat
int m,n;
u
public:
integer(int x, int y)//inline constructor

m=x; ny

The parameters of a constructor can be of any type except that


of the class to which it belongs.

Example:
class A {
's

i public:
A(A); ; 3

Programn
#include ciostream.h>
class X{
int a;
public:
X{(int j) {a
=i}
intgeta) {return a:} ard
intmain():
{

X ob 99:// passes 99 toj


cout < ob.getal): I/ outputs 99
return 0:

Visit us at http:/ www.dotcombooks4u.com


y nC Memory Manngement, Cousiricto

C. Copy Constructor s as a
copy
Constructor can accept a rcfercnce to ilsthrough a copy
parameter. The process of initializing A COPy
initialization. as itself
constructor is known as copy
the
as
samecompiler
constructor takes a reference to an object of
as an argument. When no constructor is de
supplies its own.
follows;
callcd is as same
The situations where copy constructor is object of the
() When a new objcct is initialized to
an
class.
function by valuc
(i) When an object is passed to a
from a function by vauc.
(11) When an objcct is returned
temporary ODjec
(iv) When the compiler generates a
constructor. If i1.
copy
The statement i2=i1 will not invoke the
simply asigns the
statement is legal and
and i2 are objects,
values of il to i2, member-by-member.

Thus the statement


class A {

public:
A(A &);

is valid.
In such cases constructor is called the copy
constructor.

d) Multiple Constructors in a Class


The two types of constructors as follows:
integer);// Noarguments
integer(int, int) // Two arguments

Visit us at http ://www.dotcombooks4u.com


Object Oricnted
Concepts and Programming/.
In first one, the constructor
no values are passcd itself supplics the values anu
by the calling program. datasecon as
the function call passes In
the appropriate values
C++ permits us to use form ma
both these constructors in the sane
class.

Example
class integer |
int m, n;
public:
integer() m=0; n=0;}
integer(inta, int b) {m=a; n=b;}
integer(integer & i)
m=i.m;n=i.n;}

In the above example, the program allow us to declare thrce


constructors for an integer object.

The first constructor receives no arguments, the second


receives two integer arguments and the third receives one
integer object as an argument.

The declaration integer i1; automatically invoke the first


constructor and set both m and n of il to zero.

The statement integer i2(20, 40); call the sccond constructor


which will initialize the data members m and n of i2 to 20 and
40 respectively.
Finally, the statement integer 13(2); invoke the third
constructor which copies the values of i2 into 13. It sets the
value of every data element of i3 to the valuc of the
corresponding data element of i2. 7
When more than one constructor function is defined in a class,
thee ihe constructor is overloaded:

isitus at, http:// www.dotcombooks4u.comm


OJcct, 1ynamic Memory Management, Constructo"

Program
tinclude <iostream.h>
class pwr {
double b:
int e:
double val;
public:
pwr(double base, int exp);
double getpwr() { return val:}
pwr:pwr[double base, int exp)

b base;
e = exp:
val= 1
if(exp==0) return;
*
b;
for: exp>0; exp--) val= val

int main()

pwrx(4.0, 2), y(2.5, 1), z(5.7, 0);2


t

cOut << x.get_pwr{) <<* *


cout << Y.getpwr() <<"**.
cout << z.get pwr{) <<"\n, se

return 0

C. Constructors with Default Arguments


arguments.
It is possible to define constructors with default
The constructor can be defined as follows:
complex(float real, float imag-0);

In the above form, the default value of the argument imag to


15

zero. The statement complex C(5.0); assigns the value 5.0


the real variable and 0.0 to imag (by default). The statemcnt
The
complex C{2.0, 3.0); It ssigns 2.0 to real and 3.0 to imag.
actual parameter, when spccificd, overrides the default value B
The missing arguments must be the trailing oncs. It
Visit us at hitp:/ www.dotcombooks4u.com
Object Orientcd Concepts and Programming/0

important to distinguish between the default constructor


A
A) and the default argument constructor A::
delault argument constructor can be called with cither one
A(nt
argument or no arguments. When callcd with no arguments, it
becomes a default constructor.

Program
#include <iostream.h>
class cube{
int x, y, z;
r public:
cubeint i=0, int j=0, int k=0) {
x=i;

z=k;

int volumel) {

return x'yz

int main()

clrscr():
cube a(2,3,4), b;
cOut < a.volumel) << endl
<< b.volume();
COut
return 0

f. Dynamic Constructors
t e The constructors can also be used to allocate memory while
creating objects.It enable the system to allocate the right
amount of memory for each object when the objects are not of
the same size, resulting in the saving of memory. The
allocation of memory to objects at the time of their
construction is known as dynamic construction of objects. The
memory is allocated with the help of the new operator.

Visit us at http:://.www.dotcombooks4u.com
Destruc
"clor &
Managcmcnt, Constructor
68/Mor on ++ Classes and Object, DynamicMcmory
objccts
thaj
2.3.4 Destructor the cto the
A destructor as name implies, is uscd to destroy th
construd as th
constructor. Like a ne
have been created by a name is tne
destructor is a member function whosc
i.e., ""
class name but is preceded by tilde as:~integcr) (}
program
can be defined om.practico
the
The destructor for the class integer upon exit is to
It is invoked implicitly by thc compiler space fo
spa
accessibie:emory nory
to clean up storage that is no
program
longer
since it n
relcases memory the
cmory in the
declare destructors in a uscd to allocate
future use. Whenever new is free that memory
constructors, should use delete to ws:
as tO
matrix class can be defined
The destructor for the
matrix:: ~matrix()
for(I-0;I<d1;l++)
delete pl;
delete pl
any
Characteristics of Destructor argunment nor does it return
2.3.5 takes any
a. A destructor never
a class.
value.
destructor can be defined for
Only one
b.
Destructor cannot be overloaded. objects go out of scope, a
C.
required since the pointers to
d. It is implicitly.
destructor is not called

EXERCISE
2.4
LONG ANSWER QUESTIONS accessing Member Functions
A ways of
1. Explain about different

in a class.
Friend Functions with an example.
2 Explain about
Explain about Friend Class with an example.
3.
how to access array of Class Object.
AExplain about

Visit us at
http://www.dotcombooks4u.comn
Object Oriented Concepts Programming/0
and

5. Explain how to pass Class Objects to Function and nOW


return Objects from Functions.
7. Explain about Nested Classes
with an example.
8. Explain about Namespaces with
an example.
9 Explain about Dynamic Memory Allocation and Dynamc
Memory Deallocation in C++.
10. Explain about "new" and "delete" operators with an example.

1 Explain about "Set New_Handler" Function with an example.

12 Differentiate between member function and friend function


with an example.
Differentiate between friend class and friend function with an
13.
example.
14. .Write a C++ program to create a student class with

appropriate data members and member functions


16. Write a C++ program to implement usage of Friend function
17. Write a C++ program to implement usage of Friend class

18. Write a C++ program to implement usage


ot nested classes.

19. Differentiate between nested class and friend class.


20. Write a C++ program to create a dynamic array
and print the
memory.
contents of array in reverse order and deallocate
usage of
21 Write a Ct+ program to implement the
"Set_New_Handler" function with an cxample
usage of Copy
22. Write a C++ program to implement the
Constructor, Constructor overloading and destructor.
Is it possible to overload constructor and
destructor ? Justify.
23

Visit us at http:// www.dotcombooks4u.com


Managemenl, Coustrict ot
DyuamicMemory types
ore on ++ Clnsses and Object, difforent
constructor ? ixplain
L24 What is with an example.
24. constructors
lixplain with an example.
What is destructor ? example.
25. constructor with an examnple.
lixplain copy an examp
26. overloading with an
constructor
27. Explain QUESTIONS
SHORTANSWER ?
B.
What is fricnd function
1.
What is friend class?
2
3. What is nested class?
What is namespace? operators ?,
4
use of new and delete function ?i
5. What is the Handler
Set_New_Handler
What is the role of
6.
6.
Constructor?
7.
7. What is
is
Destructor?
8. What
Constructor?
default 3
9. What is a Constructor?
Parameterized
10. What is
a
constructor?
is copy
11. What
constructor
default
12 What is
QUESTIONS
MULTIPLE CHOICE
used in situations where.
C. functions are
. 1. The friend
access private data members
to
a) We want cxchange data between classes
We want to unrelated class
bb) We want to have
access to
c bindingis required
d) Dynamic
by usins
C++ provides the
facility of function
accesscd from mord
2 members can be
which the private data
si than one class.
tearif a) static
b friend
Visit us at http:// www.dotcombooks4u.com
Object Oricnted Concepls
and Programming/

Cinline
d) virtual

3. Destructors are used to


a) the object.
initialize
b) increment

. c)
The
destroy
operator is uscd to create a heap memory space
for an object of a class.
a) new
b) delete
c) arrow

is capable of creating a new object as aa

replica of existing one.


a) copy constructor
b) destructor
c) overloaded constructor r,fstutter

6. The operator is used to destroy the variable space


which has been created dynamically
a) new
b) delete
c) arrow

D. FILL IN THE BLANKS


1. The constructor which does not accept any argument is called
as constructor.
2. The constructor used to alocate the memory to the objects at
the time of creation is called as constructor.

3. is automatically called when an object is

destroyed.

Visit us at http: / www.dotcombooks4u.com


&Destructor
Structor
72/More on ++ Classes and Object, Dynamic Menory Mauagement, Construct0
allow the
which
4. is a constructO1
ne class with
number of constructors can be defined for the s
varying argument list. which
ch is
is
function
member
5. is a special the data
values to
used to allocate memory Space and
members of that object t, t tojde fra

E. State TRUE or FALSE members of clas


ass.
public
1.
1. Friend functions have access to only
An entire class can be made a friend of anotner a
2.
using the object of that class
called
3. Tiend function cannot be
4. Destructor can be overloaded.
return any value.
5. Constructors do not
member of any of the classes.
Friend function neednot be
a
6.
symbol.
7. Destructor must be prefixed with
Constructors cannot be overloaded.
8.
copy constructor takes one argument.
9. A

***

Visit us at http:// www.dotcombooks4u.com

You might also like