Notes
Unit 2: OOP Using C++
Structure
24
22
23
24
28
268
ar
28
29
2.10
an
212
2.13
214
2.18
216
217
218
219
2.20
224
224
Introduction
Tokens
Keywords
Identifiers
Constants
Basic Data Types
User Defined Data Types
Derived Data Types
‘Symbolic Constants
‘Type Compatibility
Variables
2.11.1 Dynamic Initiaization of Variables
Reference Variables
Operations in C++
243.4 Arithmetic Operators
2.13.2 Assignment Operators
2433 Unary Operators
2.13.4. Prefix and Postfix Notations
2.13.5. Relational Operators
2.13.8 Shift Operators
2.13.7 BitWise Operators
213.8 Logical Operators
2.13.9 Conditional Operators
2.13.10 Order of Precedence of Operators
Scope resolution operator
Member dereferencing operator
Memory management operators
Manipulators
Type cast operator
Expression and their types
Operator Overioading
Control structure
Summary(00? Using C++
222 Check Your Progress
2.23 Questions and Exercises
224 Key Terms
2.25 Further Readings
Objectives
‘After studying this unit, you should be able to:
+ Understand the identifiers
+Learn the user dafine data type.
Understand basic data type.
+Learn ebout operations and expressions,
+ Understand operator and function overloading
2.1 Introduction
‘As we know, the smallest individual units in @ program are known as tokens. A C++
program is written using these tokens, white spaces, and the syntax of the language
Most of the C++ tokens are basically similar to the C tokens with the exception of some
additions and minor modifications,
2.2 Tokens
‘The smallest individual units in a program are known as tokens. The tokans of C++ are:
Keywords
Identifiers
Constants
Strings
© Operators
A C++ program is writen using these tokens, white spaces, and the syntax of the
language.
2.3 Keywords
‘The keywords implement specific C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined
program elements. Table 2.1 gives the complete sat of C++ keywords.
Table 2.1: C++ Keywords
asm double new switeh
auto else operator template:
break: enum private this
case extem protected _| throw
catch float public tn
char for register typedet
21
Notes22
Notes
(Object Oriented Programmimg wit C+
class friend return union
const goto short unsigned
continue it signed virtual
default inline size of void
delete int static volatile
oo. long struct while
2.4 Identifiers
Identifiers refer to the names of variables, functions, arrays, classes, ete., created by
the programmer. They are the fundamental requirement of any language. Each
language has its own rules for naming these identifiers.
2.5 Constants
‘Sometimes, an unchanging value or fixed value is used throughout a program. Such @
Quantity is called 2 constant. For instance, if a program deals with the area and
Circumference of circles, the constant value pi (=3 14158) would be used frequently
A constant is declared by wniting const before the keyword (@.9. int, long, float) in
the declaration
For example: const int num;(1)
Type of constant are:
‘© Integer Constants: An integer constant \ike 1768 is an int A long constant is
written with a terminal / cell / or L, as in 56704124L, an integer too big to fit into an
int will also be taken as a long. Unsigned constant are viitten with a terminal u or v,
and the suffix vor vindicate unsigned long
© Character Constants: A character is a letter, numeral, or special printing or non-
printing symbol which can be handled by the computer system. These available
symbols define the system's character set.
© Floating Point Constants: Floating point numbers are numbers that have 2
decimal point. The compiler differentiates between floating point number and
integers because they are stored differently in the computer
Exponential (Scientific) Notation: Floating point numbers may also be expressed
In Scientific notation. For example, the expression 123. 45e0 represents a floating
point number in scientific notation. It refers to the number ordinarily written as
423.45 x 106, which ts equivalent to the number 123, 450,000.
2.6 Basic Data Types
Basic data type is a data element, which is characteristic by restricting it to a particular
range of possible values. A variabie of type int, for example, may have an integer value
‘reater than or equal to some lower limit and less than or equal to some upper limi.(00° Using C++
Main Program:
‘yee antay
structure
v
Integral type Void Floating type
int char float double
Figure 2.1: Hierarchy of C++ Data Types
‘The basic data types in C++ are described in the following section:
Character denoted by char is the dala type that holds an integral value
corrasponding to the representation of an element of the ASCII character set
Integer denoted by int is the data type that nolds an integer value or a whole
umber.
Real donoted by
float is the data type that holds a single-precision floating point value or a real
umber; or
double is the data type that holds @ double-precisian floating point value or @ real
umber.
Boolean denoted by bool is the data type that holds a boolean value
of true or false
Byte is the smallest addressable memory unit. Bit, which comes trom Binary
digiT, is a memory unit that can store either a Q ora 1. A byte nas & bits, The
data type byle sizes are as follows:
© char takes 1 byte
® Int takes 2 bytes
® float takes 4 bytes
© double takes 8 bytes
qualifiers are additional attributes to a data type to possibly change the size and /
of the interpretation of the sign bit of a data type. They are as follows
© Signed which is the default value: Positive or negative values may be
assigned to 2 variable of type signed.
23
Notes24
Notes
‘Object Oriented Programming wit C+
unsigned Only positive values may be assigned to @ variable of
type unsigned
sizeof ( unsigned int ) sizeof ( int )
2 bytes = 2bytes
‘= _short which is used with int. This may change the size of
sizeof (short int) <= sizeof (int) <= __ sizeof ( long int )
bytes = 2 bytes < 4 bytes
long which is used with int and double. This changes the size
of int and double.
sizeof ( float ) sizeot (double) sizeof ( Jong double }
4 bytes < — Bbytes < 10 bytes
© Avariable is a valid ID which refers to a memory location where a value, which
may be changed, may be stored for use by 2 program. ll variables must be
declared with a name and a data type at the beginning of a block before they can
be referenced in a statement. The syntax of vanable declaration is as follows
VARIABLE-DECLARATION == { QUALIFIER | 2} TYPE ID { = INITIAL.
VALUE |23{, 1D }* 5
Example
intcount
float Number, Sum ;
float Average ;
int Count = 0, Miles
long int Velocity
long double Sum = 0
© Aconstant, which must be @ valid |D, is a memory location where @ value, which
may not be changed, may be stored for use by a program. The syntax of constant
doclaration is as follows
CONSTANT.
DECLARATION = const { QUALIFIER | 2} TYPE ID = CONSTANT-
EXPRESSION |
Example:
const float Pi= 3.1418;
const unsigned int Depth = 35800
27 User Defined Data Types
‘© Structures and Classes: User-defined data types such as struct and union are
also legal in C++, but in G++ some more features have been added to make them
suitable for object-oriented programming. C++ also permits us to define another
User-defined data type known as class which can be used, just ke any other basic
data type, to declare variables. The class variables are known as objects, which are
the central focus of object-oriented programming
‘© Enumerated Data Type: An onumerated data type is another user-defined type
which provides @ way for attaching names to numbers, thereby increasing(00° Using C++
comprehensibility of the code The enum keyword (from C) automatically
enumerates a lst of words by assigning them valuas 0, 1, 2, and so on. This facility
provides an alternative means for creating symbolic constants. The syntax of an
‘enum statement is similar to that of the struct statement
Examples: enum shape (circle, square, tangle}
2.8. Derived Data Types
© Arrays: The application of arrays in C++ is similar to that in C. The only exception
is the way character arrays are initialized
In G++, the size should be one larger than the number of characters inthe string.
chaz =
© Functions: Functions have undergone major changes in C++ While some of these
changes are simple, others require a new way of thinking when organizing our
programs. Many of these modifications and improvements were driven by the
requirements of the object-onented concept of C++. Some of these were introduced
to make the C++ program more reliable and readable. Function is briefly explained
inthe chapter 3,
© Pointer Pointers are declared and initialized as in C. Examples
int* ip; Int pointer
Ip = &x, // address of x assigned to ip
“ip = 103/50 assigned to x through indirection
(C++ adds the concept of constant pointer and pointer to a constant
char * const ptrl = "GOOD", // constant pointer
|.e,, cannot modify the address that ptr is initialized to.
int const * ptr2 = &m, / pointer to a constant
plr2 is declared as pointer to a constant. it can point to any variable of correct type,
but the contents what it points to cannot be changed. We can also declare both the
Pointer and the vanable as constants in the following way.
const char* const ep = "xy2"
‘This statement declares cp as a constant pointer to the string, which has been
declared a constant In this case, neither the address assigned to the pointer cp nor the
Contents it points to can be changad. Pointers are extensively used in C=* for memory
management and achieving polymorphism. Pointers ate briefly explained in the chapter
7
2.9 Symbolic Constants
‘There are two ways of creating symbolic constants in C++
1 Using the qualifier const
2. Defining a set of integer constants using enum kayword.
In G++, we can use const in a constant expression, such as
10
const int siz
char name|size},
const allows us to create typed constants instead of having to use #define to create
constants that have no type information.
25
Notes26
Notes
‘Object Oriented Programming wit C+
The scoping of const values differs. A const in C++ defaults to the internal linkage
and therefore it is local to the file where itis declared. In ANSI C, const values are
global in nature They are visible outside the file in which they are declared. However,
they can be made local by declanng them as static. To gve a const value extemal
linkage so that it can be referenced from another file, we must explicitly define it as an
exter in G++. Example:
exter const float total = 100,
‘Another method of naming integer constants is as follows
enum (XY Z}
This defines X.Y and Z as integer constants with values 0, 1, and 2 respectively
This is equivalent to
const X= 0
const Y= 1
const Z = 2
We can also assign values to X, Y, and Z explicitly.
enum {X = 100, Y = 50, Z = 200}
Such values can be any integer values
2.10 Type Compatibility
Both Type conversion and Type casting in C+ are used to convert one predefined
type to another type. Type Conversion is the process of converting one predefined type
into another type. and type Casting is the converting one predefined type into another
‘ype forcefully
Need of Type Conversion and Type Casting in ++
‘An Expression is composed of one or more operations and operands. Operands
consists of constants and variables. Constants and expressions of different types are
mixed together in an expression. so they afe converted to same type or says that a
conversion is necessary to convert different types into same type
Types of Type Conversions in C++
(C++ facilitates type conversion into 2 forms
‘© Implicit Type Conversion
‘© Explicit Type Conversion
Implicit Type Conversions
Implicit Type Conversion is the conversion performed by the compiler without
programmers intervention
itis applied, whenever, different data types are intermixed in an expression, so as not to
loose information.
‘The C++ compiler converts all operands upto the type of the largest operand, which
's called type promaton.(00° Using C++
Usual Arithmetic Conversions are summarized in the following table —
% Then resultant
‘StepNo. By CHMersHPE | type of other | Otherwise
operand
1 Tong double | long double ‘step2
2 double double ‘step 3
3 float float ‘Step 4
integral promotion
4 = takes place followed | —
by step 5
5 unsigned long _| unsigned long Stop 6
(long int (provided
tong intean
fepresent all values | StP7
long intant the | of unsigned int)
6 other is
(i) unsigned tong
unsignedint | iif all values of
unsigned int cant | Step 7
be represented by
tong int)
7 Tong tong Step 8
Both
8 uneioted cnsaned operandsare int
‘The step 1 and 2 in the above table will be read as —
either operand is of type long double, the other is converted to long
© step
double.
© Step2 : Othenwise, ifeither is of type double, the other is converted to double.
Aiter applying above arithmetic conversions, gach pair f operands is of same type:
land the result of each operation is the same as the type of both operands
27
Notes(Object Oriented Programmimg with C+
Example of implicit Type Conversion:
Explicit Type Conversion
Explicit Type conversion is also called type casting. It is the conversion of one operand
to @ specific type. An explicit conversion is a user defined that forces an expression to
be of specific type
‘Syntax: (type) expression
Example: float(a+b/5) ; This expression evaluates to type float,
Problem in Explicit Type Conversion
Assigning a value of smaller data type to a larger data type, may not pose any problem.
But, assigning a value of larger data type to smaller type, may poses problems. The
problem is that assigning to a smaller data type may loose information, or result in
lasing some precision
Conversion Problems
sno | Conversion Potential Problems
1 Double to float Loss of precision(significant figures)
a, Float to int Loss of fractional part(00° Using C++ 29
= (ing ta nbn Loss of Information as original valuemay be
‘out of range for target type Notes
Type Compatibility
In an assignment statement, the types of right types and left side of an assignment
should be compatible, so that conversion can take place. For example,
hex, (where ch is of char data type and xis of integer data type)
include
int main)
t
float x
x= (float) 7/5
coute=x="==x,
}
2.11 Variables
Variables are the entity whose values changes during the execution of program. We
know that, in C, all variables must be declared before they are used in executable
statements. This 's true with C++ as well C++ allows the declaration of @ variable
anywhere in the scope. This means that a variable can be declared right at the place of
its frst use. This makes the program much easier fo write and reduces the errors that
may be caused by having fo scan back and forth. It also makes the program easier to
understand because the variables are declared in the context of their use. The example
below illustrates this point
‘
Disadvantage: This siyle of declaration is that we cannot see at a glance all the
variables used in a scope.30
Notes
(Object Oriented Programming with O-+
2.14.1 Dynamic Initialization of Variables
C++, permits initialization of the variables at run time. This is referred to as dynamic
inttilization. In this, a variable can be initialized at run time using expressions at the
place of declaration. Consider the folowing valid initialization statements:
oe
float area = 3.1415
trad trad;
This means that both the declaration and initialization of a variable can be done
simultaneously at the place where the variable is used forthe first time,
The following two statements in the example of the previous section
£224 /) declaze where
can be combined into a single statement
Fae
eum /is itialize dynamically
Dynamic initalizaton is extensively used in object-oriented programming. We can
create exactly the type of object needed using information thet is known only at the run
time.
2.12 Reference Variables
Arreference variable provides an alternative name for a previously defined variable. For
example, if we make the variable sum a reference to the variable total, then sum and
‘otal can be used interchangeably to represent that variable,
A reference variable is created as follows:
data type & reference-name * variable-name
Example:
at & sum =
‘otal is @ float type variable that has already been declared, sum is the alternative name
declared to represent the variable total. Both the variables refer to the same data object
in the memory.
Initialization of reference variable:
Areference variable must be initialized at the time of declaration,
+ The statement(00° Using C++
will change the value of both total and sum to 110. Likewise, the assignment
will change the value of both the variables to zero,
A reference variable must be initialized at the time of declaration, this establishes
the correspondence between the reference and the data object that it names. Note that
the initialization of a reference variable 's completely different from assignment tok.
Note that C++ assigns additional meaning to the symbol & Here, & is not an
address operator,
‘The notation floats & means reference to float. Other examples are:
int n[to];
inte x= afl0); //x is «:
char s a=; // initialize reference to aL
‘The variable x is an altemative to the array element n[i0]. The variable a is
initiaized to the new line constant. This creates a reference to the otherwise unknown
location where the new line constant \n is stored.
‘The following references are also allowed
‘The first set of daclarations causes m to refer to x which is pointed to by the pointer
and the statement in (i) creates an int object with value 50 and name n.
Consider the following
£(m)s J
\When the function call f(m) is executed, the following initialization occurs:
Int ax sm
‘Thus x becomes an alias of m after executing the statement
£(m);
31
Notes32
Notes
(Object Oriented Programming with O-+
Such funetions calls are known as cells by reference whose implementation is
illustrated in Figure 22. Since the variable x and m are aliases, when the function
increments x, m is also incremented. The value of m becomes 20 after the function is
executed In traditional C, we accomplish this operation using pointers and
dereferencina techniques.
it met a
{po} io | ane lecation,
call ‘wo names
$4) _/_-_______«
it x=
Figure 2.2: Call by Reference Mechanism
The call by reference machanism is useful in object-oriented programming because
it permits the manipulation of objects by reference and eliminates the copying of objact
parameters back and forth. Note thal the references can be created nat only for built
Gata types but also for user-defined data types such as structures and classes.
References work wonderful well with these user-defined data types.
2.13 Operations in C++
Constant, variables, array elements function references can be joned together by
various operators to form expressions. The data items on which the operators act upon
are called operands. Some operators require two operands, whule others act upon only
‘one operand. Most operators allow the individual operands to be expressions. A few
operators permit only single variables as operands
Operators can be classified as:
‘Arithmetic operators
‘Assignment operators
Unary operators
Rwitional operators
Shift operators
Bit-wise operators
Logical operators
Conditional operators
2.13.1 Arithmetic Operators
There are five arithmetic operators in C. They are
Operator Function
+ addition
. subtraction
: muttiplication
1 division
% remainder efter integer division
Operands acted upon by artthmetic operators must represent nument values. So,
the operands can be integer, floating-point or characters. The remaindar operator (°b)
‘which is also called as modulus operator requires that both operands to be integers and(00° Using C++
the second operand be nonzero. Similarly, the division operator (/) requires that the
second operand be nonzero.
Division of one integer quantity by another is referred to as integer division
Example
Suppose that @ and b are integer variables whose values are 2 and 1, respectively
Several aritnmetic expressions involving these variables are shown below, together with
their resulting values,
Expression Value
ath 3
a-b 1
atb 2
alb 2
a%b o
Now suppose that 2 and b are floating-point variables whose values are 4.9 and
20, respectively. Several arithmetic expressions involving these variables are shown
below, together with their resulting values
Expression Value
atb 65
a-b 25
atb 9.0
alb 2.25
Operands which are differ in type may undergo type conversion before the
expression takes on its final value. In generai, the final result will be expressed in the
highest precision possible, consistent with the data type of the operands. The following
rules apply when neither operand is unsigned.
1. If both operands are floating-point types whose precision’s differ (e.g. a float and a
double), the lower-precision operand will be converted to the precision of the other
operand, and the result will be expressed in this higher precision. Thus, an
operation between a float and double will result in a double; a float and a long
double will result in a long double, and @ double and a long double will result in a
long double.
2. If one operand is a floating-point type (@ 9, float, double or long double) and the
other is a char or an int (including short int or long int), the char or int will be
converted to the floating-point type and the result will be expressed as such. Hence,
an operation between an int and a double wil result n a double.
3. if neither operand is a floating-point type but one is long int, the other will be
converted to long int and the result will be long int. Thus, an operation between &
Jong int and an int will result in a tong int
4. If neither operand is @ floating-point type or a long int, then both operands will be
Converted to int (if necessary) and the result will be int. Thus, an operation between
a short into and an int will result in an int.
33
Notes34
Notes
‘Object Oriented Programming wit C+
2.13.2 Assignment Operators
Table 2.2: Assignment operator
Operate] Desciption pe] Ewbnatin
=| Assign hevaliootinerightoperand | a= | Assgnste valusotbToa
tothe ie
+ =) Adds cperardsand assigns the reoul Addsthootbios
tothe lef operand he expression could also be writen]
asazab
~= | Subtactstre ight operand fom thee Subtacisb Forma
Sperandandstuestreresutin ele Equivalentto a= arb
peran
=| Nuitplestheletonerandey henght | —a"=0 | wutplesine vauesaande andsior|
operand and siaresiheresultin re let therecut ina
operand Equivalentto 3= a°b
Dudes te letoperanduyiherght | ab | Duesabybandstors tie esutin
opetend and staresthereoultinihe lett Equivalentto a= aro
operand
T=] Diides fe letoperandtyinengnt | ab] Dwdeesbybandebas heramande]
Dpetendandstores the remainderin ina,
thelefioperané Equivalentto a= xy
Any of the operators used as shown below
A b
that is, bis evaluated before the operation takes place.
You can also assign values to more than one variable at the same time. The
assignment will ake place from the nght to the left. For example,
A=b=0,
In the example given above, frst b willbe intialized and then a willbe initialized
2.13.3 Unary Operators:
The unary operators operate on a single operand and following are the examples of
Unary operators:
© The increment (++) and decrement (—-) operators
© The unary minus (-) operator.
© The logical nat (1) operator
‘The unary operators operate on the object for which they were called and normally,
this operator appears on the left side of the object, as in lob, -obj, and ++0bj but
sometime they can be used as postiix as well ike obj++ or obj
Table 2.3: Unary operator
Operator Deseription Bare Eiplanaion
+= nveasee The valusofiieOpeiand Dyone ae Fauna
—_Deerensnstne value tte cparand by ane quilt a=
=r(00° Using C++
2.13.4 Prefix and Postfix Notations
‘The increment operator, +=. can be used in two ways:
© Asa prefix, in which the operator precedes the variable
++ var
© As a postfix, in which the operator follows the vanable.
Ivars,
‘The following code segment differentiates the two notations:
2.13.5 Relational Operators
been
weitten aa var
Relational operators evaluate to true or false, and are used for comparing two
numbers
Table 2.4: Assignment operator
Operator [Description Bampe | Elna
Evaiateswheherthe operands areequal Retunsinueifthevauesare
equalandfaseathenise
' Evaluate swhetherthe operands arentequsl | al=y | Retumstrue tthevalues are
notequaland fase cherstse
> Evaateswheherthelettoperand isgreaier | a>b | Retumstue fais geaterbian
‘thanthe nahtoperand bandtalse
< Evayateswhethortheletoperandistessthan | a>| Shisbis tothe rant fling sianbi ate
Bipbnaion
The resulta Fis 810
eNided. by 2? An
explanatontoiows,
“The recultof his i8 10
‘multiplied by 27 An
plan atontoions,
<= _| Shitsbistotelet fingzeros atheniont
2.13.7 Bit Wise Operators
Table 2.6: Bit wise operators
‘Gperator | Description [Ean | Eptanabn
a Eralusiestoatnaivaie mera [aes | ANOweuisinal teanthonie
np) | stvsestibien re operands Set, ary ther combinabon
resasingd
7 Eyaualestobianvale aera [at | ORresuts ina Owen bobine
(om | Btvace oronme nto cperanas brs ate0, argatercomanston
rsa}
* Evuatvstoabinaryeave tora [as y | xoRsutsinaamantonts
gor | Bevacescorontnetwo cperands Spore sarovaieand Me
isha cfesetvaues
~ Comets alt bis oDeandall bts sample phontolow
anvesion | wots
2.13.8 Logical Operators
Use logical operators to combine the results of Boolean expressions.
Table 2.7: Logical operators
Operator Description Example
&& | Called Logical AND operator. Ifboth the | (A && B) is false
operands are non-zero, then condition
becomes true.
Il | Called Logical OR Operator. if any of the | (A || B) is true.
two operands is non-zero, then condition
bacomes true
1 | Called Logical NOT Operator. Use to NA 88 8) 1s true,
reverses the logical state of its operand. IF
‘a condition is true, then Logical NOT
operator will make false.
2.13.9 Conditional Operators
Table 2.8: Conditional operators
Operator [Description Beare Emhnation
(conditon)| Evauatastovalt iMheconditon | a= @c) ? be | Asassignedinevauent, fo
vat ,va12|retums true andvat 2 ifthe contin Is greater than c, else ais
retrnstalse assignedthevaiue of.(00° Using C++
This example finds the maximum of two given numbers,
= (numl > aund)
In the above program code, we determine whether numt is greater than num2. The
variable, imax is assigned the value, numt, if the expression, (num >um2), evaluates
to true, and the value, num2, if the expression evaluates to false. The above program
code can be modified using the conditional operator as
Imax = (num > num2)? num : num2;
‘The ?: Operator is called the ternary operator since it has three operands.
2.13.10 Order of Precedence of Operators
The table shows the order of precedence of operators. Those with the same level of
precedence are listed in the same row. The order can be changed by using
parentheses at appropriate places
Type Operators
High Precedence 00
Unary
Multiplicative *1%
Additive +
Shift
Relational
Equality
Bitwise
Logical
Conditional 2
Assignment =
‘The unaty operators, assignment operators and the conditional operator group from
the right to the left. All other operators group from the left to the right,
2.14 Scope resolution operator
The scope resolution (-) operator is used to qualify hidden names. One can use the
unary scope operator if a namespace scope or global scope name Is hidden by an
‘explicit declaration ofthe same name ina block or class
37
Notes38
Notes
(Object Oriented Programming with C++
For example:
int count = 0;
int main(void)
{
int count = 0,
1 {1 set global count to 4
count
count = 2; 1/ sat local count to 2
return 0
}
Program explanation
© count declared in the main () function hides the integer namad count declared
In global namespace scope
©The statement 1 accesses the variable named count declared in
global namespace scope
Consider an another exampl
In this the declaration of the variable x hides the class type x, but you can still use the
static class member by qualifying it with the class type x and the scope
resolution operator
#include x | | m
Bitwise expressions: It manipulates date at bit level Example. a >> 4 and b<< 2
Pointer expressions: It ives address values as output are. Example, &, ptr.
‘Special assignment expressions: |t can be categorized further depending upon
the way the values are assigned to the variables
Chained assignment: It is an assignment expression in which the same value
is assigned to more than one variable, by using a single statement,
Example: a = (b=20);
In the example describe above, first the value 20 is assigned to variable b and
then to variable a
Embedded assignment: itis an assignment expression, which is enclosed
within another assignment expression,
Example: a=20+(b=30)
Inthe example descnbe above, the value 30 is assigned to variable b and then
the resull of (20+ 30) is assigned to variable a
= Compound Assignment: Itis an assignment expression, which uses a
compound assignment operator which iS @ combination of the assignment
‘operator with a binary arithmetic operator.
Example-a + =20
In the example describe above, the operator += is a compound assignment
‘operator, also known as short-hand assignment operator(00° using C++
2.20 Operator Overloading
Operator overloading is one of the most exciting features of object onented
programming. It can transform complax, obscure program listings into intuitively obvious
ones.
For example, a statement like
3. add objects (41, 2)
can be changed to the much more readable
d3sa1+a2,
‘The rather forbidding term operator overloading refers to giving the normal C++
operators, such as +. *, <=, and += additional meanings when they are applied to user-
defined data types. Normally
+0
Works only with basic types like int and float, and attempting to apply it when a, b,
and ¢ are objects of a user-defined class will cause complaints from the compiler.
However, using overloading. You can make this statement legal even when a, b and c
are user defined types.
In effect, operator overloading gives you opportunity to work, you can change C++
‘operators to do whatever you want. By using classes to create new kinds of variables,
and operator overloading to create new definitions for operators, you can extend C++ to
be, in many ways, a new language of your own design.
Another kind of operation, data types Conversion, is closely connected with
operator overioading. C++ handles the conversion of simple types, like int and float,
automatically, but conversions involving user-defined types require some work on the
programmer's part
The general form of an operator function is
where returniype is the type of value returned by the specified operation and op is
the operator being overioaded. The op is preceded by the keyword operator. operator
op is the funetion name.
Operator functions must be either member functions (non-static) or friend functions,
A basic difference between them is thet a friend function will have only one argument
‘or unary operators and two for binary operators, while a member function has no
arguments for unary operators and only one for binary operators. This is because the
object used to invoke the member function is t_sed implicitly and therefore is available
for the member function, This is not the case with frend functions. Arguments may be
passed either by value or by reference
‘The process of overloading involves the following steps:
© First, create a class that defines the data type that is to be used in the overloading
operation
© Declare the operator function operator op ( ) in the public part of the class. Itmay be
either a member function or a friend function
© Define the operator function to implement the required operations.
Overloaded operator functions can be invoked by expressions such as
41
Notes42
Notes
Otjct Oriented Programming wth C++
op x or x op
for unary operators and
xopy
for binary operators.
0 x (or x op) would be interpreted as
operator op (x)
for friend function! Similarly, the expression x op y would be interpreted as either
x operator oP(Y)
in case of member functions, or
operator op (x, y)
in case of friend functions. When both the forms are declared, standard argument
matching is applied to resolve any ambiguity,
This operator changes the sign of an operand when applied to an object in much
the same way as is applied to an int or float variable. The unary minus when applied to
{an object should change the sign of each of its data items.
2.21 Control structure
The flow of control jumps from one part of the program to another, depending on
calculations performed in the program. Program statements that cause such jumps are
called Controf statements
There are two major categories of control statements
4. Decisions
2. Loops
Decisions
In. program a decision causes a one-time jump to a different part of the program,
dapending on value of an expression. Decisions can be made in C= = in several ways,
such a8 if else statement, simple if statement, switch statement and consitional
operator
The if Statement
The if statement is the simplest of the decision statements. Our next program provides
an example,
1) dex
cee
<
void maia ()
cout <<
is greater than(00° Using C++
The if keyword is followed by a test expression in parentheses. The syntax of if is
very much like that of while. The difference is that the statements following the if are
‘executed only once if the test expression is true; the statements following while are
executed repeatedly until the test expression becomes false. The output of above
program is
Ourpur
Enter a number: 120
‘That number is greater than 100
eo
if the number entered is less than 100, the program will terminate without prating
anything
Test False
Expression
y
True
Body off
———
Figure 2.3: Operation of if statement
The if else Statement
‘The if... else statement is used when we want to do one thing if a condition is true
and do something else ifs false. It consists of an if statement, followed by a statement
r block of statements, followed by the keyword else, followed by another statement or
block of statements.
Hore’s a variation of our pravious IF example, with an alse added to the if
/ ite
// cencnsteates ifsles statens
# include
43
Notes44
Notes
(Object Oriented Programmimg with C+
Output
Or ifelse
Enter @ number: 300
That number is greater than 100
> else
Enter a number: 30”
That number is less than 100
co
Bony oft Boayofene
Figure 2.4: Operation of the if.....else statement
Nested if
The loop and decision structures, we've seen so far, can be nested inside one another.
You can nest ifs inside loops, loops inside ifs, ifs inside ifs, and so on,
Here’s an example, PRIME, that nests an if within a for loop. This example tells yo if
‘a number you enter Is a prime number.(00° Using C++
unsigned long ny 3 +
Output
1 22231
er divisible by 11
‘This program accepts a number from user that is assigned to n. It then uses a for
loop to divide n by all numbers from 2 upto n/2. The divisor is j, the loop variable. if any
value of | divides evenly into n, then n Is not prime and the remainder is 0. so the %
‘operator in if statement is used to test for this condition with each value j. If the number
's not prime, it tells the user and exit from the program.
Nested
else Statements
‘An if statement can be nested inside an if. else statement, which can be nested inside
another if.. else statement, which can be nested inside yet another if_.else statement
land so on. Ifthe first test condition is false, the second one is examined and so on until
all the conditions have been checked. if anyone proves true, the appropriate action 1s
taken. Such a nested group of f..else statements is called a decision tree.
Example
void main( )
£
intade
clrser(y;
45
Notes46 (Object Oriented Programmimg with C+
cout <<"enler 3 number’
Notes cinssa>>b>>c;
iffa>b)
{
if(a>c)
{
cout <<"a is greatest’,
d
alse
{
cout <<" is greatest’
d
y
else
{
if(b> 0)
{
cout <= "b is greatest’;
I
else
4
printt(c is greatest’)
y
}
geten(),
}
Else it
The general form of else.sf ladder is,
iffexpression 1)
(
statement-block1,
}
else iffexpression 2)
{
statement-block2;
}(00° Uking C++
se ifexpression 3 )
‘
statoment-block3,
,
else
detault-statement,
‘The expression is tested from the top(of the ladder) downwards. As soon as the
true condition is found, the statement associated with itis executed.
Example:
void main( )
t
inte
cout << "enter a number";
cina> a;
cout << “divisible by both § and &"
)
else if a:
ce
cout << “divisible by:
,
else if(a%s:
(
cout << “divisible by 5",
)
else
fe
cout << “divisible by none”
)
getehd,
,
The Switeh Statement
Ifyou nave a large decision tree, and all the decisions depend on the value of the same
variable, you will find a switch statement more useful than @ series of if
tions. Here's a simple example
else construc-
47
Notes48
Notes
(Object Oriented Programmimg with C+
// denonaceates switch scacement
#idclade e/iestream.ch >
cous << “M
coue << “High speed \n”
This program prints one of three possible messages depending on whether the user
inputs the number 23, 45, or 78. The keyword switch is followed by a switch variable in
parentheses
switch (speed)
Braces then delimit a number of case statements. Each case keyword is followed
by a constant, which is not in parentheses but is followed by a colon
case 33
The data type of the case constants should match that of the switch variable
Before enterng the switch, the program should assign a value to the switch
variable This value will usually match @ constant in one of the case statements. When
this is the case, the statements immediately following the keyword case will be
executed, until a break is reached
Output of the above program is
Enter 23, 45 or 78 : 45
Medium speed
co(00° Using C++
The break Statement
Previous program has a break statement at the end of each case section. The break
keyword causes the entire switch statement to exit. Don't forget the break, without i
control passes down (or “falis through’) to the statements for the next case, which is
usually not what you want.
If the value of the switch variable doesn't match any of the case constants, then
control passes to the end of the switch without doing anything. The break keyword is
also used fo escape from loops.
# include
# include < conio -h > getene ()
<< ch
Notice that break only takes you out of the innermost loop. This is true no matter
what constructions are nested inside each other break only takes you out of the
construction in which its embedded. if there were a switch within a loop, a break in the
‘switch would only take you out of the switch, not out of the loop
49
Notes50
Notes
(Object Oriented Programming with C++
Continue
Continue statement works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place,
skipping any code in between,
For the for loop, continue causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, program control passes to the
conditional tests.
Syntax
The syntax of a continue statement in C++ is:
continue;
Flow Diagram:
> a
if condition
is true
if condition
is false
Example:
#include a>
Body ot foop
v
Increment
exgression
Figure 2.5: Operation of the for loop
The while Loop
The for loop does something a fixed number of times. If you don't know how many tines
yyou want to do something before yau start the loop, the iuhile loop is used
Hore is a program to demonstrate the use of while loop
ed to
ca numbers
ude <
anip.h > uw
53
Notes54
Notes
(Object Oriented Programmimg with C+
The output of the above program is
1
8
ar
64
125
216
343
512
728
The next number would be 1000, but by this time the loop has terminated
The while loop contains a test expression but no initialization or increment expres-
sions. As long as the test expression is true, the loop continues to be executed. In the
above example, the test expression is true until pow> 999.
Although thera is no initialization expression, the loop variable (here pow) must be
intalized before the loop begins. The loop body must also contain some statement that
changes the value of the loop variable, otherwise the loop would never end
The do Loop
Ina while loop, the test expression is evaluated at the beginning of the loop. If the test
expression is false when the oop Is entered, the loop body won't be executed at all
Sometimes you want to guarantee that the loop body is executed at least once, no
matter what the initial state of the test expression. In this case, you should use do loop,
which places the test expression at the end of the loop.
Consider the program aiven below to demonstrate the use of do loop
ates DO Lo!
void main ((00° Using C++
cour <<
‘The keyword do marks the beginning of the loop. Braces delimit the body of the
loop and a while statement provides the test expression and terminates the loop.
Following each computation, the above program asks if the user wants to do
another. if yes, the user enters a ‘character, and the test expression:
Chien
remains true. |f user enters ‘r’, the test expression becomes false and the loop
torminates.
The
Figure 2.6: Operation of do-loop
2.21 Summary
‘Smallest individual units in @ program are known as tokens. The kaywords implement
specific C++ language features. Identifiers refer to the names of variables, functions,
arrays, classes, etc , created by the programmer. A constant is an entity which do not
change during the execution of program, and 1s declared by writing const before the
keyword (e.g int, long, foat) in the declaration
Basic data type is a data element, which is characteristic by restricting it to a
particular range of possible values. Variables ere the enlily whose values changes
during the execution of program.
C++, permits initialization of the variables at run time. This is referred to as dynamic
initialization. A reference variable provides an alternative name for a previously defined
variable. Constant, variabies, array elements function references can be joined together
by various operators fo form expressions.
55
Notes56
Notes
‘Object Oriented Programming wit C+
Variable which stores the address of another variable is called a pointer, that "point
to" the variable whose address they store. An expression is @ combination of variables,
constants and aperators that represents a computation
2.22 Check Your Progress
Multiple Choice Questions
1. The size_t integer type in C++ is?
4) Unsigned integer of at least 64 bits
) Signed integer of at least 16 bits
c) Unsigned integer of at least 18 bits
d) Signed integer of at least 64 bits,
2. What is the output ofthe following program?
#include
using namespace std
intmaing,
t
intx= 4
unsigned int y
ifle> ye
cout << "xis greater"
pelse {
cout << is greater’
}
,
a) x is greater
b) ys greater
c) Implementation defined
d) Avbitrary
3. Which of these expressions will retum true if the input integer v is a power of two?
avlw+t))
b&w)
cywlwed
)(v&(v-1)
4. What isthe value of the following 6-bit integer afterall statements are executed?
intx=
xeet:
xe,
a) 1
by a
©) 127
d) Implementation defined
5. Which of these expressions will make the rightmost set bit zero in an input integer
”O0P Using C++
a) x=) (e1)
b) x=x & (x1)
©) x=x| (1)
4d) x=x8 Oe)
6. Which of these expressions will solate the rightmost set bit?
a) x=x&(-x)
b) x= x8 (x)
c) x=K a(x)
d) x=x" (x)
7. 0948, 786427373824, ‘x’ and OX2t are
respectively
a) decimal, character, octal, hexadecimal
b) octal, hexadecimal, character, decimal
) hexadecimal, octal, decimal, character
4) octal, decimal, character, hexadecimal
8. What will be the output of this program?
#include
using namespace std,
int maing)
t
inta = 8,
cout <<"ANDing integer’ with ‘true":" << a && true;
retum 0,
}
a) ANDing integer ‘a’ with ‘true’ 2
b) ANDing integer ‘a’ with ‘true’ 0
©) ANDing integer “a with ‘rus’ :1
d)_ None of the mentioned
9. What will be output of this program?
#include
using namespace std;
int main)
{
inti= 3;
int =i /-2,
intk =i %-2
cout <<1 <