Ooops Chapter 4
Ooops Chapter 4
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.
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:
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
(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
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
variable_nam This
reference
For examplename-n
is the name of
variable
int a =10
Now, we variable.
create the variable of the
above
The
int
&ref a,
referen
=
#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; =
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;
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 -
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;
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
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)
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
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-
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;
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:
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
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+
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
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;
The dereferencing
the object and the member. INC using the
is used
invoked
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
#include<conio.h>
class M
int x
int y;
public:
void set_xy(int a, int b)
x-a
y-b
int sum(M m)
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
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;
int sum(M m)
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