0% found this document useful (0 votes)
13 views14 pages

Ooops Chapter 4

Uploaded by

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

Ooops Chapter 4

Uploaded by

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

68 Ohject Oriented

Program with C
YBSe1.T) (Sen
UNIT-1
Operators
and
A References in C++
CHAPTER

SYNOPSIS
4.1 Introduction
4.2
Scope Resolution Operator
4.3 Reference Variables
4.4 The Bool Data Type
45 The Operalor New and
Delete
4.5.1 The New
Operator
4.5.2 The Delete
Operator
4.6 Malloc vs Ne
4.7 Pointer
Member Operators

4.1 INTRODUCTION
C+has a rich set of operators. All c Operators are valid in C++ also.
in addition, C++ introduces some new operators. We have already seen two such
operators, namely, the insertion operator <<, and the extraction operator >>.
Other new operators are:
Scope Resolution Operator
Pointer-to-member declarator
Pointer-to-member operator
Pointer-to-member operator
delete Memory Release Operator
end Line feed Operator
new Memory Allocation Operator
setw Field width Operator
In addition, C++ also allows us to provide new definitions to some of the built-in operators.
That is, we can give several meanings to an operator, depending upon the types of arguments used
This process is known as Operator Overloading.

4.2 SCOPE RESOLUTIONOPERATOR


So far, we have seen that the member functions and member variables were defined in the
class specifier.
a) Scope resolution operator used in member variables
The :: (scope resolution) operator is used to qualify hidden names so that you can still use
them.
and References in Ct+
p e r a o r sa n dRen
69
general syntax is:
The

HVariable_name

e is
Operator allows access to the global version of a variable.
Example :

#include iostream.h>

Hincludesconio.h>

=
10;
int a Wglobal variable
int m a i n )

int a = 20;
lla redeclared, local to main
cout"Local Variable :" <<a<<\n"
cout<Global iable:"<<:a<<"\n";
using scope resolution operator
return 0;

Output:

Local Variable :20


Global Variable: 10

oDe
Scope resolution operator used in member functions:
b)
When more ember functions are added to a clas specifier, it becomes bulky and difficult to
ndle.
cTIch times it is useful
At to keep only the function declarations within the class
c the functions outside it. To tell the
complier that a
specifier and
e function is a member of a class it has to be
dec
lared within the class specifier or it can be defined outside
the class specifier using a scope
resolutio operator : ((double colon symbol) with the
function definition.
The general syntax for using member
TH functions outside a class
specifier is:
return_type class name: : member functions(arg1, arg2,.., argn)
The type of member function arguments must exactly match with the
specifier.
type declared in the class
Only the scope operator identifies the function as a member of a particular class.
Example:
#include <iostream.h>
#include<conio.h>
class programming

public:
void output); //function declaration

I/ function definition outside


the class
void programming:: output()

cout< "Function defined outside the


class.In"
6E.Y.B.Sc. (L.T.)- Object Oriented
Programming with C++ (Sem.-I)
B.Sc.-1.T)
(FYB.S

(Sem-I)
C+

70 P r o g r a m m i n
with

Oriented
Obict
int main)

prreturn
x.ooutgrpautmmi
(0:)D ng
4.3 REFERENCEVA
a.
WhenENCE VARIABLES a l e r m a u v e
name for an
an d e c l a r a t i o n n

becomes
the
a variab it "& n

variable. A iable can b red as a


reference,

declared as a
reference by
puting
location. We can
eate a
hen we create a some
memory

ariable
variable by
by Using
referenceof of the dole;lable, then it
occupies
access
the original eithep
name therefore, we can

the variable
variable reference.
the
Synta
Here,
r
tax : datatyp
atype & refer
or
or

eference name =
variable_name;
/

float etc.
reference variable

datatype -The datatypeofvariable like int,


char,

variable_nam This
reference
For examplename-n
is the name of
variable

* Ihe name of reference variable.


given by
user.

int a =10
Now, we variable.
create the variable of the
above

The
int
&ref a,
referen
=

variababovein statement means that 'reff is areference var


ariable of 'a', i.e., we can use the 'ref

#i#ivoidnnclcluumainde<coni
de<io0stroeam..h>hP
place of 'a' variable.

int a= 8,
int &b= a
cou The varia
riable a :
cout< The "<<a<<endl
getchO, reference variable
ariable ref:
re "<<b;

Output:
The variable a : 8
Ihe
reference variable ref: 8

e above program, a variable of integer type is declared and initialized witha value.

int a8; =

The variable b is declared which is referring variable a.


int &b = a;
Operators and References in
C++
properties of References
The
following are theproperties of references
Initialization
I t must be
initialized at tthe time of the declaration.
inta-10;// variable initialization
int
&cb=a; // b reference to a
aration. tae code, we have created a reference variable, ie., 'b'. At the time of
declaration, 'a' variable is assigned to 'b'.
w e do
not assign at the time of declaration, then the code would look like :
int &b;
&b-a,
n e above code will throw
It cannot be
a compile-time eror as 'a' is not assigned at the time of declaration.
2. reassigned means that the reference variable cannot be
int x=11;// variable initialization modined
int z-67;
int &y-x,lly reference to x
int &y=z, l/y reference to z, but throws a
compile-time error.
In the above code, 'y' reference variable is
referring to 'x variable,and then 'z is assigned to
y'.But this reassignment is not possible with the reference variable, so it throws a
error.
compile-timne
3. Function Parameters
References can also be passed as a function parameter. It does not create a copy of the
argument and behaves as an alias for a parameter. It enhances the performance as it does not create
a copy of the argument.
#include<iostream.h>
#include<conio.h>
void main0

int a-9;// variable initialization


int b=10;//variable initialization
swap (a, b); // function calling
cout "value of a is :" <<a<<endl;
cout < "value of b is :" <<b<<endl;
getch 0;

void swap (int &p, int &q) // function definition

int temp; // variable declaration

temp-p

9-temp,

Output:
value of a is: 10

value of bis:9
70
ww Ohject Oriented
Programming with CH+ Sc.-1.T) (Sem.-ln
(FYB,Se-17

int main)

programming x
x.output(0
return 0;

4.3 REFERENCE VARIABLES


When variable is declared as
a name for an
exist
alternative .

it becomes an
variable. A variable a a
reference,
reference,
e & i n the declaratio
tion.
can be declared as a reference byby putting
putting
When we declared relci ation. We ccanant
location.
create a some memor)y create
reference of the variable, then it it occupies
occuples access the
original variable using eithera
by using
name of the variable; therefore,
nerefore, we can
can we
variable or reference.
Syntax: datatype & / reference variable
Here, datatype reference
rence_name
The datatype
= variable_name;
of variable like int, char, float etc.
variable_name - This is the name of variable given by user.
reference_name -

The name of reference


variabic
For example:
int a =10;
Now we
create the
reference variable of the above variable.
int &ref =a;
a ve statement means that 'ref is a reference variable of 'a, i.e., we can use the're
variable in place of'a'
variable.
#include<iostream.h
#include<conio.h>
void main 0

int a =
8;
int &&b =a,
cout< The variable a :
"<<a<<endl;
cout< The reference variable ref: "<<b;
getchO;

Output
The variable a : 8
The reference
variable ref:8
In the above program, a variable of integer type is declared and initialized with a value.
int a = 8;

The variable b is declared which is


referring variable a.

int &b a;
pera
rators and References in C++

eroperties of References
The following are the properties of references
Initialization
I t must be initialized at the time ofthe declaration.
int a-10;// variable initialization
int &b-a; //b reference to a
"b. At the uime
have created reference varíable, i.e.,
c aDOve code, we a

ACclaration,'a' variableis assigned to 'b'.


look lHke :
I we do not assign at the time of declaration, then the code would
int &b;
&b-a,
time of declaration.
The above code will throw a compile-time error as 'a' is not assigned at the
It cannot be reassigned means that the reference variable cannot be modified.

int x=11;// variable initialization


int z-67;
int &y=x;/y referenceto x
int &y-z;//y reference to z, but throws a compile-time error.
then 'z is assigned to
In the above code, 'y' reference variable is referring to x variable, and
so it throws a compile-time
. But this reassignment is not possible with the reference variable,
error.

3 Function Parameters

References can also be passed as a function parameter. It does not create a copy of the
does not create
argument and behaves as an alias for a parameter. It enhances the performance as it
a copy of the argument.

#include<iostream.h>
#include<conio.h>
void main)

int a-9;// variable initialization


int b=10; // variable initialization

swap (a, b); // function calling


cout "value of a is :" <<a<<endl;
cout<"value of b is :" <<b<<endl;
getch 0

void swap (int &p, int &g) // function definition

int temp; /l variable declaration

temp-p;

q=temp,

Output:
value of a is : 10
value ofb is: 9
2
Programming
with C'
(YB.Se-lT

.T) (Sem
Oriented
Ober
4.4 THE BOOL
DATA
The
TYPE data types
the orig
to theoriginal c
ISOANSI C++ Standard has added certain
new

specifications addeu
as well as
well as for
provid=
They are
provided to in certain
situations

conveniences to C++ provide better


control

A boolean programmers. and can only take the value


data type is the bool
keyword
either true declared with is bool.
false form. One of
or
t new data types
of the ne
The language.
values true or false have been added in the C++
as keywords
added as e variable with true value.
ebeen

Syntax: bool bl true; / =

Important Points declari


boolean
a

1. The default
numeric value of true is 1 and 0.
2 Ne can use bool-type variables or values true and false tai in mathemaical expressions
al
For instance,
int x= false
is valid and the expression+true
+
3. 6
on the right will evaluate to 7 as false has a value of0 and t-

will have a value of 1.


I t is also possible to convert implicitly the data type integers or tloating-point values

bool type.
Example:
bool x=0; // false
bool y =
100; l/ true
bool z= 15.75; / true
oSt common use of the bool datatype is for conditional statements. We can compa

n d l t i o n s with a boolean, and also return them telling if they are true Or raise.

Program
#include <iostream.h>
#includeconio.h>
void main)

int x1 =
10, x2 20, m =2;
bool b1, b2;

I/ false
bl =x1 =x2;

/ true
b2-x1 < x2;

cout "Bool1 is =" <<bl << "n";

cout << "Bool2 is ="<<b2 << "n";


bool b3 = true;

if (b3)
cout << "Yes" <<"n";

else
cout << "No" << "n":
Operators and References in Ct* 73
Int x3 false +5 * m -b3;

Cout <x3;

ng getch):
In

Output:
Booll is=0

Bool2 is=1
Yes
9
0
4.5 THE OPERATOR NEW AND DELETE
An object is created when its definition appears in a program and it is destroyed when its
e
name goes out of scope or the program terminates.
It is often useful to create a new object that will exist only as long as it is needed.
to
In C++, the operator new creates such objects and the operator delete can be used to
destroy them later.
Objects allocated by new and delete are said to be on the free store.
4.5.1 The New Operator
The new operator is used to create a memory space for an object of a class.
The new operator returns a pointer to the object created.
e
General syntax for new operator is:

data type pointer_variable =new data type;


wheredata_type can be a short int, float, char or even class objects.
For example
int *p; l/pointer to integer type
float *f llpointer to a float type
p-new int; / allocates memory for an integer
fnew float; ll allocates memory for a float
I f the operator new is successful, it returns a pointer to the space that is allocated.
Otherwise, it returns zero if the space is not available or if some error is detected.
T h e above syntax can also be used to allocate memory for an object.
Example: Class student
Student *stu_ptr; //pointer to an object of type student
stu_ptr = new Student; l/points to new Student object.

The above statements create an object of type Student using the new operator and return a
pointer to it, which is assigned to stu_ptr.
Note: The new operator is similar to the malloc() function used in C. The new operator is
superior in that it returns a pointer to the appropriate data type, while malloc)'s pointer
must be cast to the appropriate type.
4.5.2 The Delete Operator
I f we allocate memory when we create an object, we need to de-allocate the memory when
the object is no longer needed.
with CH+ (YB Se
delete. The space

Programming
74 '' Object Oriented
An 0oject created by new exists until it is explicitly destroyed by dete

occupied by the object can then be reused.


The general syntax for the delete operator is:
h e n c e
we

delete pointer variable; m e m o r y


and

the variable to remove


it from Om

in
The operator delete uses the address of
associate it with a pointer variable.
and delete
The following code shows the simplest use of new
int ptr
ptr-new int

ptr-12;
cout<ptr Wnen youaare
space
delete ptr to return
memory
t o refer
ce to memory
operator
delete used
It is always good practice to
a use
pointers
are not
so that
through with it. Care should be taken using a similar
lengtn
that has been deleted.
consisting of
arrays of varying
to allocate blocks
sPpOSSible
for deleting
an
array
technique. Note the use of delete[]

Example
int *ptr,
ptr-new int[100];
delete I ptr
MALLOC VIS NEW allocate the memory.
4.6 used to dynamically
malloc ) both are 1s the operator, used a s a
.

that new
Ihe
new and new and malloc (0 is
used to allocatte
between library function,
The primary difference a standard
the malloc ) is
construct. On the other hand,
memory at runtime.
MALLOC 0
NEW
COMPARISON
malloc () is a feature of
specific
new is a The function
The operator C.
Language feature of C++,
Java, and C#.
function.
malloc() is a
operator.
Nature "new" is an
reference_variable
=
new
int ptr (data_type)|
Syntax type malloc(sizeof(data_type);
type name
malloc requires the sizeof operator to
new doesn't need the sizeof know what memory size it has to allot.
sizeof() allots enough memory
operator as it
for specific type.
new can call the malloc() cannot at all make a call to a
Constructor Operator constructor.
constructor of an object.
initialization could not be
Initialization The operatornew could initialize
an Memory
to done in malloc.
object while allocating memory
t
The malloc ) can never be
Overloading Operator new can be overloaded.
overloaded.
OperatorWs and References C+

Fallure On failure, operator new throws an


75
exception. On failure, malloc ()
returns a NULL
Deallocation The memory
deallocated usingallocation
"delete". by new, The memory
Reallocation The new operator is deallocated allocation by malloc
using free( ) function.O|
a

reallocate memory. does not Memory


allocated by malloc
Execution
The reallocated using realloc (). ) can be
operator new cuts the
execution time. The malloc ( )
requires more time for
execution.
4.7 POINTER MEMBER
C++ provides two
OPERATORS
pointer operators, which are-
a) Address of
Operator&
b) Indirection Operator".
A pointer is a variable that
variable that contains the address contains the address of
of another another variable or you can say that
variable can be any data type including an variable is said to "point to" the other variable. Aa
The. object, structure or
again pointer itself.
(dot) operator and the >
classes, structures, and unions. (arrow) operator are used to reference individual members of
The Address of Operator &
The & is a
unary operator that returns the
integer variable, memory address of its
address. This operator has the operand. For example, if var
is an then &var is its
left associativity as the other unary same
precedence and right-to-
operators.
You should read the &
operator as "the address of" which
address of var". means &var will be read as "the
The Indirection Operator*
The second operator is indirection
Operator *, and it is
operator that returns the value of the variable located at the the complement of &. It is a unary
address its specified by operand.
Pointers to Members
I t is possible to take the address of a member of a class and
address of a member can be obtained by assign it to a
pointer. The
class member name. A class member applying the operator & to a "fully qualified
the class name. pointer can be declared using the operator with

Example:
class A

private:
int m,
public:
void show):

We can define a
pointer to the member m as follows:
int A::* ip = &A :: m;

The ip pointer created thus acts like a class member in that it must be invoked with a
class object. In the statement
above, the phrase A::* means "pointer-to-member of A
class"
)
C
9'9P Object Oriented Program with
The phrase &A:m means the "address of the m member ofA class
Remember, the following statement is not valid i l i
w h e n

only
appled to
int ip &m, /won't work meaning
be

int type data. It has n


m u s t

This is because m is not simply an perator

which it belongs. The scope oper


(op
associated with the class to
fiunctions

and the member.


m e m b e r functio
tion.
pointer
both the inside
member

used to access the member


m
in a a memo
T h e pointer ip can now be
red

ofA declae
assume that a is an object
friend functions). Let us
follows
We can access m using the pointer ip as
couts a. ip: /display
/same as above
couts a.m;

Now, look at the following code :


objecta
to
pointer
ap- &a /ap is
/display m
cout ap->ip: polnters
to b0th
/same as above use
We
cout ap->m: member
when
the object
itself
when
a
is used is used
access
->* to
The dereferencing operator operator.*

The dereferencing
the object and the member. INC using the
is used
invoked

pointer. Note that *ip can be


then
used member
with the which
functions

pointers to member
We can deign
also below
in the main as shown
dereferencing operators
pointer-to-member function) (10
(object-name.
->* pointer-tò-member
function) (0 thesis are necessary.
pointer-to-object
and ->*,
the parenthe
so

The precedence (0 is higher than that of.*


Program:
Fincludeiostream.h>

#include<conio.h>

class M

int x
int y;
public:
void set_xy(int a, int b)

x-a
y-b

friend int sum(M m);

int sum(M m)

int M::* px =&M:: x


int M::* py- &M: y;

M *pm-&m;
int S = m.*px + pm->*Py;

return S,
Operators md Refirences in C
17
void main)

Mn:
void M:: "p)int, int) &M:: set xy:
(n."pOC10,20)
coute"SUM=" <<Sum(n) <<"\n";
M op &n;
(op-"p30,40);
cout<"SUM=" <<sum(n) <<"n";
getch);

Output:
SUM 30
SUM 70
9'99 Objeet Orientel Programming with C
The phrase &A:m means the "address of the m member of A
class
Remember, the following statement is not valid I1 is
int ip&m; //won't work when
to
only appled

be
This is because m is not simply an int type data.
m e a n i n g

must

operator

associated with the class to which it belongs. The scope oper fiunctions (o
both the pointer and the member.
side
m e m b e r

function
The pointer ip can now be used to access the member m inst in a
m e m b e r

triend functions). Let us assume that a is an object of A declarc


d e c l a r e d

We can access m using the pointer ip as follows:


coutee a."ip: /display
cout<< a.m /same as above

Now, look at the following code a


to object
ap- &a; /ap is pointer
cout<< ap ->ip: //display m
/same as above ers to both
pointers
coutc< ap->m when
we
use

member
the object itself i
a
The dereferencing operatoror->* is used to access used
when

operator
.* is
the object and the member. The dereferencing member
name.

a
used like
used with the member pointer. Note that *ip is can be
invoked using the
which then
We can also deign pointers member functions
to
shown below
dereferencing operators in the main as
(object-name. pointer-to-member function) (10);
(l0%
pointer-to-object->* pointer-tò-memberfunction) are necessary.
so the parenthesis
ne precedence ( is higher than that of.* and ->*,

Program:
#include<iostream.h>
#include<conio.h>
class M

intx
int ys
public:
void set_xy(int a, int b)

x-a
y=b;

friend int sum(M m);

int sum(M m)

int M::* px = &M :: X;

int M::* py= &M: y;


M #pm= &m;
int S= m."px + pm-"py;
return S
Operators md Referenees in C
7

void main)

Mn
void ( M:: *p)int, int) &M :set
xy;
(n. pfC10,20);
coute"'SUM- <<sum(n) <"n":
"

M #op &n;
(op->"p30,40);
cout<"SUM= <sum(n) <<"in":
"

getch);

Output:
SUM = 30

SUM 70

You might also like