oop with c++

Posted on at

1. Introduction :
What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C
and C++.
2. C++ Programming basics :
Output using cout. Directives. Input with cin. Type bool. The setw
manipulator. Type conversions.
3. Functions :
Returning values from functions. Reference arguments. Overloaded
function. Inline function. Default arguments. Returning by reference.
4. Object and Classes :
Making sense of core object concepts (Encapsulation, Abstraction,
Polymorphism, Classes, Messages Association, Interfaces)
Implementation of class in C++, C++ Objects as physical object, C++
object as data types constructor. Object as function arguments. The
default copy constructor, returning object from function. Structures
and classes. Classes objects and memory static class data. Const
and classes.
5. Arrays and string arrays fundamentals. Arrays as class Member
Data :
Arrays of object, string, The standard C++ String class
6. Operator overloading :
Overloading unary operations. Overloading binary operators, data
conversion, pitfalls of operators overloading and conversion
keywords. Explicit and Mutable.
7. Inheritance :
Concept of inheritance. Derived class and based class. Derived
class constructors, member function, inheritance in the English
distance class, class hierarchies, inheritance and graphics shapes,
public and private inheritance, aggregation : Classes within classes,
inheritance and program development.
8. Pointer :
Addresses and pointers. The address of operator and pointer and
arrays. Pointer and Faction pointer and C-types string. Memory
management : New and Delete, pointers to objects, debugging
9. Virtual Function :
Virtual Function, friend function, Static function, Assignment and copy
initialization, this pointer, dynamic type information.
10. Streams and Files :
Streams classes, Stream Errors, Disk File I/O with streams, file
pointers, error handling in file I/O with member function, overloading
the extraction and insertion operators, memory as a stream object,
command line arguments, and printer output.
11. Templates and Exceptions :
Function templates, Class templates Exceptions
12. The Standard Template Library :
Introduction algorithms, sequence containers, iteators, specialized
iteators, associative containers, strong user-defined object, function
Term work / Practical : Each candidate will submit a journal in which at
least 10 assignments based on the above syllabus and the internal paper.
Test will be graded for 10 marks and assignments will be graded for 15
1. Object Oriented Programming in C++ by Robert Lafore Techmedia
2. The complete reference C – by Herbert shieldt Tata McGraw Hill
3. Object Oriented Programming in C++ Saurav Sahay Oxford University
4. Object Oriented Programming in C++ R Rajaram New Age
International Publishers 2nd.
5. OOPS C++ Big C++ Cay Horstmann Wiley Publication.
Practical for C++
Programming exercises and project using C++ programming
languages, to study various features of the languages. Stress to be laid
on writing well structured modular and readable programs accompanied
by good documentation.
The topic wise assignments are as follows :
1. Function Blocks
a. Handling default reference arguments
b. Handling inline and overloaded function
2. Objects and Classes
a. Creating UDT using classes and object
3. Arrays and String as objects
a. Insertion, Deletion, reversal sorting of elements into a single
Unit Structure
1.1 Introduction of C++
1.2 Object-Oriented Programming
1.3 Encapsulation
1.4 Polymorphism
1.5 Inheritance
1.6 The Need for C++
1.7 Characteristics of OOPs
1.8 C++ and C
The history of C++ begins with C. C++ is built upon the
foundation of C. Thus, C++ is a superset of C. C++ expanded and
enhanced the C language to support object-oriented programming
(which is described later in this module). C++ also added several
other improvements to the C language, including an extended set
of library routines. However, much of the spirit and flavor of C++ is
directly inherited from C. Therefore, to fully understand and
appreciate C++, you need to understand the “how and why”
behind C.
C++ was invented by Bjarne Stroustrup in 1979, at Bell
Laboratories in Murray Hill, New Jersey. He initially called the new
language “C with Classes ” However in 1983 the name was
changed to C++ Stroustrup built C++ on the foundation of C
including all of C’s features attributes and benefits He also adhered
to C’s underlying philosophy that the programmer not the language
is in charge t this point it is critical to understand that Stroustrup did
not create an entirely new programming language. Instead, he
enhanced an already highly successful language.
Most of the features that Stroustrup added to C were
designed to support object-oriented programming. In essence, C++
is the object-oriented version of C. By building upon the foundation
of C, Stroustrup provided a smooth migration path to OOP. Instead
of having to learn an entirely new language, a C programmer
needed to learn only a few new features before reaping the benefits
of the object-oriented methodology
Central to C++ is object-oriented programming (OOP). OOP
was the impetus for the creation of C++ Because of this it is useful
to understand OOP’s basic principles before you write even a
simple C++ program.
Object-oriented programming took the best ideas of
structured programming and combined them with several new
concepts. The result was a different and better way of organizing a
program. In the most general sense, a program can be organized in
one of two ways: around its code (what is happening) or around its
data (who is being affected). Using only structured programming
techniques, programs are typically organized around code. This
approach can be thought of as “code acting on data ”
Object-oriented programs work the other way around. They
are organized around data, with the key principle being “data
controlling access to code ” In an object -oriented language; you
define the data and the routines that are permitted to act on that
data. Thus, a data type defines precisely what sort of operations
can be applied to that data.
To support the principles of object-oriented programming, all
OOP languages, including C++, have three traits in common
encapsulation, polymorphism and inheritance. Let’s examine each.
Encapsulation is a programming mechanism that binds
together code and the data it manipulates, and that keeps both safe
from outside interference and misuse. In an object-oriented
language, code and data can be bound together in such a way that
a self-contained black box is created. Within the box are all
necessary data and code. When code and data are linked together
in this fashion, an object is created. In other words, an object is the
device that supports encapsulation.
Polymorphism (from Greek meaning “many forms”) is the
quality that allows one interface to access a general class of
actions. A simple example of polymorphism is found in the steering
wheel of an automobile. The steering wheel (the interface) is the
same no matter what type of actual steering mechanism is used.
That is, the steering wheel works the same whether your car has
manual steering, power steering, or rack-and-pinion steering. Thus,
turning the steering wheel left causes the car to go left no matter
what type of steering is used. The benefit of the uniform interface
is, of course, that once you know how to operate the steering
wheel, you can drive any type of car.
The same principle can also apply to programming. For
example, consider a stack (which is a first-in, last- out list). You
might have a program that requires three different types of stacks.
One stack is used for integer values, one for floating-point values,
and one for characters. In this case, the algorithm that implements
each stack is the same, even though the data being stored differs.
In a non–object-oriented language, you would be required to create
three different sets of stack routines, with each set using different
names. However, because of polymorphism, in C++ you can create
one general set of stack routines that works for all three situations.
This way, once you know how to use one stack, you can use them
Inheritance is the process by which one object can acquire
the properties of another object. This is important because it
supports the concept of hierarchical classification. If you think about
it, most knowledge is made manageable by hierarchical (that is,
top-down) classifications. For example, a Red Delicious apple is
part of the classification apple, which in turn is part of the fruit class,
which is under the larger class food. That is, the food class
possesses certain qualities (edible, nutritious, and so on) which
also, logically, apply to its subclass, fruit. In addition to these
qualities, the fruit class has specific characteristics (juicy, sweet,
and so on) that distinguish it from other food. The apple class
defines those qualities specific to an apple (grows on trees, not
tropical, and so on). A Red Delicious apple would, in turn, inherit all
the qualities of all preceding classes and would define only those
qualities that make it unique.
Without the use of hierarchies, each object would have to
explicitly define all of its characteristics. Using inheritance, an
object need only define those qualities that make it unique within its
class. It can inherit its general attributes from its parent. Thus, it is
the inheritance mechanism that makes it possible for one object to
be a specific instance of a more general case.
Given the preceding discussion, you might be wondering
why C++ was invented. Since C was a successful computer
programming language, why was there a need for something else?
The answer is complexity. Throughout the history of programming,
the increasing complexity of programs has driven the need for
better ways to manage that complexity. C++ is a response to that
need. To better understand the correlation between increasing
program complexity and computer language development, consider
the following. Approaches to programming have changed
dramatically since the invention of the computer.
For example when computers were first invented
programming was done by using the computer’s front panel to
toggle in the binary machine instructions. As long as programs
were just a few hundred instructions long, this approach worked. As
programs grew, assembly language was invented so that
programmers could deal with larger, increasingly complex
programs by using symbolic representations of the machine
instructions. As programs continued to grow, high-level languages
were developed to give programmers more tools with which to
handle the complexity.
The first widely used computer language was, of course,
FORTRAN. While FORTRAN was a very impressive first step, it is
hardly a language that encourages clear, easy-to-understand
programs. The 1960s gave birth to structured programming, which
is the method of programming encouraged by languages such as
C. With structured languages it was, for the first time, possible to
write moderately complex programs fairly easily. However, even
with structured programming methods, once a project reaches a
certain size, its complexity exceeds what a programmer can
manage. By the late 1970s, many projects were near or at this
In response to this problem, a new way to program began to
emerge: object-oriented programming (OOP). Using OOP, a
programmer could handle larger, more complex programs. The
trouble was that C did not support object-oriented programming.
The desire for an object-oriented version of C ultimately led to the
creation of C++.
In the final analysis, although C is one of the most liked and
widely used professional programming languages in the world,
there comes a time when its ability to handle complexity is
exceeded. Once a program reaches a certain size, it becomes so
complex that it is difficult to grasp as a totality. The purpose of C++
is to allow this barrier to be broken and to help the programmer
comprehend and manage larger, more complex programs.
OOP offers several benefits to both the program designer and the
user. The principal advantages are.
1) Emphasis is on data rather than procedure.
2) Programs are divided into what are known as objects.
3) Data structures are designed such that they characterize the
4) Functions that operate on the data of an object are tied together
in the data structure.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added wherever
8) Follows bottom up approach in program design.
9) Through inheritance, we can eliminate redundant code and
extend the use of existing classes
10) We can build program from the standard working module that
communicate with one another, rather than having to start
writing the code from scratch. This leads to saving of
development time and higher productivity.
11) The principal of data hiding helps the programmer to build
secure programs that cannot be invaded by code in other part
of the program.
12) It is possible to have multiple instance of an object to co-exist
without any interference
13) It is easy to partition the work in a project, based on objects.
14) Object oriented systems can be easily upgraded from small to
large systems.
15) Message passing techniques for communication between
objects makes the interface description with external systems
much simpler.
16) Software complexity can be easily managed.
1.8 C++ AND C
 C is procedure oriented programming & c++ is object
oriented programming.
 C is top to bottom programming approach; c++ is bottom to
top programming approach.
 C ++ has inheritance concept but c has not inheritance
 C is structured design, c++ is object oriented design
 C input/output is based on library and the processes are
carried out by including functions.
 C++ I/O is made through console commands cin and cout.
 Undeclared functions in c++ are not allowed. The function
has to have a prototype defined before the main() before use
in c++ although in c the functions can be declared at the
point of use.
 Although it is possible to implement anything which C++
could implement in C, C++ aids to standardize a way in
which objects are created and managed, whereas the C
programmer who implements the same system has a lot of
liberty on how to actually implement the internals, and style
among programmers will vary a lot on the design choices
Unit Structure
2.1 Some of the important concepts in oops are
2.2 Basic Data Types in C++
2.3 Variables in C++
2.4 Operators in C++
1) Objects
2) Classes
3) Data abstraction & Encapsulation.
4) Inheritance
5) Polymorphism
6) Dynamic binding.
7) Message passing.
2.1.1 Object:-
i) Objects are the basic run-time entities in an object-oriented
ii) They may represent a person, a place a bank account, a table of
data or any item that the program has to handle.
iii) Programming problem is analyzed in terms of objects and the
nature of communication between them.
iv) Objects take up space in the memory & have an associated
address like structure in c.
v) When a program executes, the object interacts by sending
messages to one another.
Ex. If there are two objects “customer” and “account”, then the
customer object may send a message to the account object
requesting for the bank balance. Thus each object contains data,
and code to manipulate the data.
2.1.2 Classes
i) The entire set of data and code of an object can be made a userdefined data type with the help of a class. Objects are actually
variable of the type class.
ii) Once a class has been defined, we can create any number of
objects belonging to that class. Thus a class is collection of
objects of similar type.
iii) Classes are user defined data types and behaves like the built in
type of a programming language.
iv) The syntax for defining class is class class-name
2.1.3 Data abstraction and Encapsulation
i) The wrapping up of data and functions into a single unit called
class is known as encapsulation.
ii) The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it.
iii) These functions provide the interface between the objects data
and the program. This insulation of the data from direct access
by the program is called data hiding or information hiding.
iv) Abstraction refers to the act of representing essential features
without including the background details or explanations.
v) Classes use the concept of abstraction and are defined as a list
of abstract attributes such as size, weight and coast, and
functions to operate on these attributes.
2.1.4 Inheritance
i) Inheritance is the process by which object of one class acquire
the properties of objects of another class.
ii) In OOPs, the concept of inheritance provides the idea of
reusability. This means that we can add additional features to
an existing class without modifying it.
iii) This is possible by deriving a new class from the existing one.
The new class will have combined features of both the classes.
2.1.5 Polymorphism
i) Polymorphism is important oops concept. It means ability to take
more than one form.
ii) In polymorphism an operation may show different behavior in
different instances. The behavior depends upon the type of data
used in the operation.
For Ex- Operation of addition for two numbers, will generate
a sum. If the operands are strings, then the operation would
produce a third string by concatenation.
iii) The process of making an operator to show different behavior in
different instance is called as operator overloading. C++ support
operator overloading.
2.1.6 Dynamic Binding
i) Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
ii) Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time.
2.1.7 Message Passing
i) OOPs consist of a set of objects that communicate with each
ii) Message passing involves following steps
iii) Creating classes that define objects and their behavior
iv) Creating objects from class definitions and
v) Establishing communication among objects.
vi) A message for an object is a request for execution of a
procedure & therefore will invoke a function in the receiving
object that generates the desired result.
Message passing involves specifying the name of the object,
the name of the function i.e. message and the information to be
Ex customer. balance(account no)
object message information
A First Simple C++ Program
# include
int main()
cout<<.Hello World.;
return 0;
} 
C++ program is a collection of functions. Every C++ program
must have a main() function.
 The iostream file:-
The header file iostream should be included at the beginning
of all programs that uses one output statement.
 Input / Output operator
1. Input Operator cin :-
The identifier cin is a predefined object in c++ that
corresponds to the standard input stream. Here this stream
represents keyboard.
Syntax:- cin>>variable;
The operator >> is known as extraction or get from operator
& assigns it to the variable on its right.
2. Output operator cout :-
The identifier cout is predefined object that represents the
standard output stream in c++. Here standard output stream
represents the screen.
Syntax:- cout< The operator << is called the insertion or put to operator. It
inserts the contents of the variable on its right to the object on its
3. Return type of main():-
In C++, main returns an integer type value to the operating
system. So return type for main() is explicitly specified as int.
Therefore every main() in c++ should end with a return 0 statement.
C++ Data Types
User defined type Built in type Derived type
Structure Array
Union Function
Class Pointer
Enumeration reference
Integral Type void Floating type
int char Float double
1) Integral type : – The data types in this type are int and char.
The modifiers signed, unsigned, long & short may be applied to
character & integer basic data type. The size of int is 2 bytes and
char is 1 byte.
2) void – void is used
i) To specify the return type of a function when it is not returning
any value.
ii) To indicate an empty argument list to a function.
Ex- Void function1(void)
iii) In the declaration of generic pointers.
EX- void *gp
A generic pointer can be assigned a pointer value of any
basic data type.
Ex . int *ip // this is int pointer
gp = ip //assign int pointer to void.
A void pointer cannot be directly assigned to their type
pointers in c++ we need to use cast operator.
Ex - Void * ptr1;
Char * ptr2;
ptr2 = ptr1;
is allowed in c but not in c++
ptr2 = (char *)ptr1
is the correct statement
3) Floating type:
The data types in this are float & double. The size of the float
is 4 byte and double is 8 byte. The modifier long can be applied to
double & the size of long double is 10 byte.
User-defined type:
i) The user-defined data type structure and union are same as
that of C.
ii) Classes – Class is a user defined data type which can be used
just like any other basic data type once declared. The class
variables are known as objects.
iii) Enumeration
a) An enumerated data type is another user defined type which
provides a way of attaching names to numbers to increase
simplicity of the code.
b) It uses enum keyword which automatically enumerates a list of
words by assigning them values 0, 1, 2,..etc.
c) Syntax:-
enum shape {
Now shape becomes a new type name & we can declare
new variables of this type.
EX . shape oval;
d) In C++, enumerated data type has its own separate type.
Therefore c++ does not permit an int value to be automatically
converted to an enum value.
Ex. shape shapes1 = triangle, // is allowed
shape shape1 = 2; // Error in c++
shape shape1 = (shape)2; //ok
e) By default, enumerators are assigned integer values starting
with 0, but we can over-ride the default value by assigning some
other value.
EX enum colour {red, blue, pink = 3}; //it will assign red to o, blue
to 1, & pink to 3 or enum colour {red = 5, blue, green}; //it will
assign red to 5, blue to 6 & green to 7.
Derived Data types:
1) Arrays
An array in c++ is similar to that in c, the only difference is
the way character arrays are initialized. In c++, the size should be
one larger than the number of character in the string where in c, it is
exact same as the length of string constant.
Ex - char string1[3] = “ab”; // in c++
char string1[2] = “ab”; // in c.
2) Functions
Functions in c++ are different than in c there is lots of
modification in functions in c++ due to object orientated concepts in
3) Pointers
Pointers are declared & initialized as in c.
Ex int * ip; // int pointer
ip = &x; //address of x through indirection
c++ adds the concept of constant pointer & pointer to a constant
char const *p2 = .HELLO.; // constant pointer
Next you have a summary of the basic fundamental data
types in C++, as well as the range of values that can be
represented with each one:
Name Description Size* Range*
Char Character or
small integer
1byte signed: -128 t127
unsigned: 0 to 255
short int
Short Integer. 2bytes signed: -32768 to 32767
unsigned: 0 to65535
Int Integer. 4bytes signed: - 2147483648 to
unsigned: 0 to 4294967295
long int
Long integer. 4bytes signed: -2147483648 to
unsigned: 0 to 4294967295
Bool Boolean value. It
can take one of
two values: true
or false.
1byte true or false
Float Floating point
4bytes 3.4e +/- 38 (7 digits)
double Double precision
floating point
8bytes 1.7e +/- 308 (15 digits)
Long double
precision floating
point number.
8bytes 1.7e +/- 308 (15 digits)
wchar_t Wide character. 2bytes 1 wide character
Declaration of variables.
C requires all the variables to be defined at the beginning of
a scope. But c++ allows the declaration of variable anywhere in the
scope. That means a variable can be declared right at the place of
its first use. It makes the program easier to understand.
In order to use a variable in C++, we must first declare it
specifying which data type we want it to be. The syntax to declare a
new variable is to write the specifier of the desired data type (like
int, bool, float...) followed by a valid variable identifier.
For example: int a;
float mynumber;
These are two valid declarations of variables. The first one
declares a variable of type int with the identifier a. The second one
declares a variable of type float with the identifier mynumber. Once
declared, the variables a and mynumber can be used within the
rest of their scope in the program.
If you are going to declare more than one variable of the
same type, you can declare all of them in a single statement by
separating their identifiers with commas.
For example: int a, b, c;
This declares three variables (a, b and c), all of them of type
int, and has exactly the same meaning as: int a;
int b;
int c;
The integer data types char, short, long and int can be
either signed or unsigned depending on the range of numbers
needed to be represented. Signed types can represent both
positive and negative values, whereas unsigned types can only
represent positive values (and zero). This can be specified by using
either the specifier signed or the specifier unsigned before the type
For example: unsigned short int Number OfSisters;
signed int My Account Balance;
By default, if we do not specify either signed or unsigned
most compiler settings will assume the type to be signed, therefore
instead of the second declaration above we could have written:
int MyAccountBalance;
with exactly the same meaning (with or without the keyword
An exception to this general rule is the char type, which
exists by itself and is considered a different fundamental data type
from signed char and unsigned char, thought to store characters.
You should use either signed or unsigned if you intend to store
numerical values in a char-sized variable.
short and long can be used alone as type specifiers. In this
case, they refer to their respective integer fundamental types: short
is equivalent to short int and long is equivalent to long int. The
following two variable declarations are equivalent:
short Year;
short int Year;
Finally, signed and unsigned may also be used as
standalone type specifiers, meaning the same as signed int and
unsigned int respectively. The following two declarations are
unsigned NextYear;
unsigned int NextYear;
To see what variable declarations look like in action within a
program, we are going to see the C++ code of the example about
your mental memory proposed at the beginning of this section:
Scope of variables:
All the variables that we intend to use in a program must
have been declared with its type specifier in an earlier point in the
code, like we did in the previous code at the beginning of the body
of the function main when we declared that a, b, and result were of
type int.
A variable can be either of global or local scope. A global
variable is a variable declared in the main body of the source code,
outside all functions, while a local variable is one declared within
the body of a function or a block.
Global variables can be referred from anywhere in the code,
even inside functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed
in braces ({}) where they are declared. For example, if they are
declared at the beginning of the body of a function (like in function
main) their scope is between its declaration point and the end of
that function. In the example above, this means that if another
function existed in addition to main, the local variables declared in
main could not be accessed from the other function and vice versa.
Dynamic initialization of variables.
In c++, a variable can be initialized at run time using
expressions at the place of declaration. This is refereed to as
dynamic initialization.
Ex int m = 10;
Here variable m is declared and initialized at the same time.
Reference variables
i) A reference variable provides an alias for a previously defined
ii) Example:-
If we make the variable sum a reference to the
variable total, then sum & total can be used
interchangeably to represent that variable.
iii) Reference variable is created as:-
data type & reference name = variable name.
Ex int sum = 200;
int &total = sum;
Here total is the alternative name declared to represent the
variable sum. Both variable refer to the same data object in
iv) A reference variable must be initialized at the time of
v) C++ assigns additional meaning to the symbol .&..Here & is not
an address operation. The notation int & means referenceto int.
A major application of reference variable is in passing
arguments to functions.
Ex void fun (int &x) // uses reference
x = x + 10; // x increment, so x also incremented.
int main( )
int n = 10;
fun(n); // function call
When the function call fun(n) is executed, it will assign x to
ni.e. int &x = n;
Therefore x and n are aliases & when function increments x.
n is also incremented. This type of function call is called call by
Introduction to strings:
Variables that can store non-numerical values that are
longer than one single character are known as strings.
The C++ language library provides support for strings
through the standard string class. This is not a fundamental type,
but it behaves in a similar way as fundamental types do in its most
basic usage.
A first difference with fundamental data types is that in order
to declare and use objects (variables) of this type we need to
include an additional header file in our source code: and
have access to the std namespace (which we already had in all our
previous programs thanks to the using namespace statement).The
following initialization formats are valid for strings:
string mystring = “This is a string”;
string mystring (“This is a string”);
Strings can also perform all the other basic operations that
fundamental data types can, like being declared without an initial
value and being assigned values during execution.
2.4.1 Assignment (=):
The assignment operator assigns a value to a variable.
This statement assigns the integer value 5 to the variable a.
The part at the left of the assignment operator (=) is known as the
lvalue (left value) and the right one as the rvalue (right value). The
lvalue has to be a variable whereas the rvalue can be a constant, a
variable, the result of an operation or any combination of these.
The most important rule when assigning is the right-to-left rule: The
assignment operation always takes place from right to left, and
never the other way:
a= b
This statement assigns to variable a (the lvalue) the value
contained in variable b (the rvalue). The value that was stored until
this moment in a is not considered at all in this operation, and in
fact that value is lost.
2.4.2 Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and
division literally correspond with their respective mathematical
operators. The only one that you might not be so used to see may
be modulo; whose operator is the percentage sign (%). Modulo is
the operation that gives the remainder of a division of two values.
For example, if we write:
a = 11 %3
The variable a will contain the value 2, since 2 is the
remainder from dividing 11 between 3.
2.4.3 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=,
&=, ^=, |=)
When we want to modify the value of a variable by
performing an operation on the value currently stored in that
variable we can use compound assignment operators:
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
2.4.4 Increase and decrease (++, --)
Shortening even more some expressions, the increase
operator (++) and the decrease operator (--) increase or reduce by
one the value stored in a variable. They are equivalent to +=1 and
to -=1, respectively. Thus:
are all equivalent in its functionality: the three of them increase by
one the value of c.
A characteristic of this operator is that it can be used both as
a prefix and as a suffix. That means that it can be written either
before the variable identifier (++a) or after it (a++). Although in
simple expressions like a++ or ++a both have exactly the same
meaning, in other expressions in which the result of the increase or
decrease operation is evaluated as a value in an outer expression
they may have an important difference in their meaning: In the case
that the increase operator is used as a prefix (++a) the value is
increased before the result of the expression is evaluated and
therefore the increased value is considered in the outer expression;
in case that it is used as a suffix (a++) the value stored in a is
increased after being evaluated and therefore the value stored
before the increase operation is evaluated in the outer expression.
Notice the difference:
Example1 Example 2
B=3; B=3;
A=++B; A=B++;
Outpu //A contains 4 //A contains 3, B contains 4
In Example 1, B is increased before its value is copied to A.
While in Example 2, the value of B is copied to A and then B is
2.4.5 Relational and equality operators ( ==, !=, >, <, >=, <= ):
In order to evaluate a comparison between two expressions
we can use the relational and equality operators. The result of a
relational operation is a Boolean value that can only be true or
false, according to its Boolean result.
We may want to compare two expressions, for example, to
know if they are equal or if one is greater than the other is. Here is
a list of the relational and equality operators that can be used in
Operators Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Here there are some examples:
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Of course, instead of using only numeric constants, we can use
any valid expression, including variables. Suppose that a=2, b=3
and c=6,
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
Be careful! The operator = (one equal sign) is not the same
as the operator == (two equal signs), the first one is an assignment
operator (assigns the value at its right to the variable at its left) and
the other one (==) is the equality operator that compares whether
both expressions in the two sides of it are equal to each other.
Thus, in the last expression ((b=2) == a), we first assigned the
value 2 to b and then we compared it to a, that also stores the
value 2, so the result of the operation is true.
2.4.6 Logical operators ( !, &&, || ):
The Operator ! is the C++ operator to perform the Boolean
operation NOT, it has only one operand, located at its right, and the
only thing that it does is to inverse the value of it, producing false if
its operand is true and true if its operand is false. Basically, it
returns the opposite Boolean value of evaluating its operand.
For example:
!(5 == 5) // evaluates to false because the expression at its right
(5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
The logical operators && and || are used when evaluating
two expressions to obtain a single relational result. The operator &&
corresponds with Boolean logical operation AND. This operation
results true if both its two operands are true, and false otherwise.
The following panel shows the result of operator && evaluating the
expression a && b:
a b a && b
true true true
true false false
false true false
false false false
The operator || corresponds with Boolean logical operation OR.
This operation results true if either one of its two operands is true,
thus being false only when both operands are false themselves.
Here are the possible results of a || b:
a b a || b
true true true
true false true
false true true
false false falseFor example:
( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).
2.4.7 Conditional operator ( ? )
The conditional operator evaluates an expression returning a
value if that expression is true and a different one if the expression
is evaluated as false. Its format is:
condition ? result1 : result2
If condition is true the expression will return result1, if it is not
it will return result2.
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
2.4.8 Comma operator ( , ):
The comma operator (,) is used to separate two or more
expressions that are included where only one expression is
expected. When the set of expressions has to be evaluated for a
value, only the rightmost expression is considered.
For example, the following code:
a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to
variable a. So, at the end, variable a would contain the value 5
while variable b would contain value 3.
2.4.9 sizeof()
This operator accepts one parameter, which can be either a
type or a variable itself and returns the size in bytes of that type or
a = sizeof (char);
This will assign the value 1 to a, because char is a one-byte
long type.
The value returned by sizeof is a constant, so it is always
determined before program execution.
Some of the new operators in c++ are-
1. :: Scope resolution operators.
2. ::* pointer to member decelerator.
3.  * pointer to member operator.
4. .* pointer to member operator.
5. delete memory release operator.
6. endl Line feed operator
7. new Memory allocation operator.
8. stew Field width operator.
Scope resolution Operator.
1) C++ is a block - structured language. The scope of the variable
extends from the point of its declaration till the end of the block
containing the declaration.
2) Consider following program.
{ int x = 1;
{ int x = 2;
} =====
The two declaration of x refer to two different memory
locations containing different values. Blocks in c++ are often
nested. Declaration in a inner block hides a declaration of the same
variable in an outer block.
3) In C, the global version of a variable cannot be accessed from
within the inner block. C++ resolves this problem by using scope
resolution operator (::), because this operator allows access to the
global version of a variable.
4) Consider following program.
# include
int m = 10;
int main ( )
int m = 20;
int k = m;
int m = 30;
cout << .K = . < cout << .m = .< cout << : : m = . << : : m;
cout << .m. = .<< m;
cout << .::m = <<::m;
return 0;
The output of program is
k = 20
m = 30
:: m = 10
m = 20
:: m =10
In the above program m is declared at three places. And ::m
will always refer to global m.
5) A major application of the scope resolution operator is in the
classes to identify the class to which a member functions
Member dereferencing operators .
C++ permits us to define a class containing various types of
data & functions as members. C++ also permits us to access the
class members through pointers. C++ provides a set of three
pointer. C++ provides a set of three pointers to member operators.
1) ::* - To access a pointer to a member of a class.
2) .* - To access a member using object name & a pointer
to that member.
3) * - To access a member using a pointer in the object &
a pointer to the member.
Memory management operators.
1) We use dynamic allocation techniques when it is not known in
advance how much of memory space is needed. C++ supports
two unary operators new and delete that perform the task of
allocating & freeing the memory.
2) An object can be created by using new and destroyed by using
delete. A data object created inside a block with new, will
remain existence until it is explicitly destroyed by using delete.
3) It takes following form.
variable = new data type
The new operator allocated sufficient memory to hold a data
object of type data-type & returns the address of the object.
EX p = new int.
Where p is a pointer of type int. Here p must have already been
declared as pointer of appropriate types.
4) New can be used to create a memory space for any data type
including user defined type such all array, classes etc.
Ex int * p = new int [10]
Creates a memory space for an array of 10 integers.
5) When a data object is no longer needed, it is destroyed to
release the memory space for reuse. The general form is delete
variable. If we want to free a dynamically allocated array, we must
use following form.
delete [size] variable.
The size specifies the no of elements in the array to be freed.
6) The new operator has following advantages over the function
malloc() in c -.
i) It automatically computes the size of the data object. No need to
use sizeOf()
ii) If automatically returns the correct pointer type, so that there is
no need to use a type cast.
iii) new and delete operators can be overloaded.
iv) It is possible to initialize the object while creating the memory
Manipulators are operators that are used to format the data
display. There are two important manipulators.
1) endl
2) stew
1) endl : -
This manipulator is used to insert a linefeed into an output. It
has same effect as using .\n. for newline.
Ex cout<< .a. << a << endl <<.n=. < << endl<<.p=.< The output is
a = 2568
n = 34
p = 275
2) Setw : -
With the stew, we can specify a common field width for all
the numbers and force them to print with right alignment.
EX cout< The manipulator setw(5) specifies a field width of 5 for
printing the value of variable sum the value is right justified.
3 5 6
Type cast operator.
C++ permits explicit type conversion of variables or
expressions using the
type cast operator.
Syntax . type name (expression)
Ex avg = sum/float(i)
Here a type name behaves as if it is a function for converting
values to a designated type.
Unit Structure
3.1 Introduction :
3.2 if – else Statement
3.3 Nested ifs :
3.4 The switch Statement
3.5 The for Loop
3.6 The while Loop
3.7 The do-while Loop
3.8 Using break to Exit a Loop
3.9 Using the goto Statement
This module discusses the statements that control a
program’s flow of execution. There are three categories of :
selection statements, which include the if and the switch; iteration
statements, which include the for, while, and do-while loops; and
jump statements, which include break, continue, return, and goto.
Except for return, which is discussed later in this book, the
remaining control statements, including the if and for statements to
which you have already had a brief introduction, are examined
The complete form of the if statement is
if(expression) statement
else statement
where the targets of the if and else are single statements.
The else clause is optional. The targets of both the if and else can
also be blocks of statements. The general form of the if using
blocks of statements is
statement sequence
statement sequence
If the conditional expression is true, the target of the if will be
executed; otherwise, the target of the else, if it exists, will be
executed. At no time will both be executed. The conditional
expression controlling the if may be any type of valid C++
expression that produces a true or false result.
This program uses the ‘if’ statement to determine whether
the user’s guess matches the magic number. If it does, the
message is printed on the screen. Taking the Magic Number
program further, the next version uses the else to print a message
when the wrong number is picked:
int main()
int magic;// magic number
int guess;// users guess
magic = rand(); // get a random number
cout << “Enter your guess”
cin >> guess;
if (guess == magic) cout << “Right”;
else cout<< “ sorry , your are wrong”;
return 0;
A nested if is an if statement that is the target of another if or
else. Nested ifs are very common in programming. The main thing
to remember about nested ifs in C++ is that an else statement
always refers to the nearest if statement that is within the same
block as the else and not already associated with an else.
The general form of the nested if using blocks of statements is
statement sequence
statement sequence
statement sequence
statement sequence
Here is an example
if(j) result =1;
if(k) result =2;
else result = 3;
else result = 4;
The final else is not associated with if(j) (even though it is the
closest if without an else), because it is not in the same block.
Rather, the final else is associated with if(i). The inner else is
associated with if(k) because that is the nearest if. You can use a
nested if to add a further improvement to the Magic Number
program. This addition provides the player with feedback about a
wrong guess.
The second of C++’s selection statements is the switch. The
switch provides for a multiway branch. Thus, it enables a program
to select among several alternatives. Although a series of nested if
statements can perform multiway tests, for many situations the
switch is a more efficient approach. It works like this: the value of
an expression is successively tested against a list of constants.
When a match is found, the statement sequence associated with
that match is executed. The general form of the switch statement is
{ case constant 1 :
Statement sequence
case constant 2 :
Statement sequence
case constant 3 :
Statement sequence
Statement sequence
The switch expression must evaluate to either a character or
an integer value. (Floatingpoint expressions, for example, are not
allowed.) Frequently, the expression controlling the switch is simply
a variable. The case constants must be integer or character literals.
The default statement sequence is performed if no matches
are found. The default is optional; if it is not present, no action takes
place if all matches fail. When a match is found, the statements
associated with that case are executed until the break is
encountered or, in a concluding case or default statement, until the
end of the switch is reached.
There are four important things to know about the switch
The switch differs from the if in that switch can test only for
equality (that is, for matches between the switch expression and
the case constants), whereas the if conditional expression can be
of any type.
No two case constants in the same switch can have identical
values. Of course, a switch statement enclosed by an outer switch
may have case constants that are the same.
A switch statement is usually more efficient than nested ifs.
The statement sequences associated with each case are not
blocks. However, the entire switch statement does define a block.
The importance of this will become apparent as you learn more
about C++.
The following program demonstrates the switch. It asks for a
number between 1 and 3, inclusive. It then displays a proverb
linked to that number. Any other number causes an error message
to be displayed.
using namespace std;
int main()
int num;
cout<< “Enter a number from 1 to 3”;
cin >>num;
case 1:
cout << “ A rolling stone gathers no moss.\n”;
case 2:
cout<< “ A bird in hand is worth two in the bush.\n”;
case 3:
cout<< “ A full and his money soon parted.\n”;
default :
cout<< “ you must enter 1 , 2 or 3.\n”;
return 0;
Here is a sample run
Enter a number from 1 to 32
A bird in hand is worth two in the bush.
You have been using a simple form of the for loop since
Module 1. You might be surprised at just how powerful and flexible
the for loop is. Let’s begin by reviewing the basics, starting with the
most traditional forms of the for.
The general form of the for loop for repeating a single statement is
for(initialization; expression; increment) statement;
For repeating a block, the general form is
for(initialization; expression; increment)
statement sequence
The initialization is usually an assignment statement that
sets the initial value of the loop control variable, which acts as the
counter that controls the loop. The expression is a conditional
expression that determines whether the loop will repeat. The
increment defines the amount by which the loop control variable will
change each time the loop is repeated. Notice that these three
major sections of the loop must be separated by semicolons. The
for loop will continue to execute as long as the conditional
expression tests true. Once the condition becomes false, the loop
will exit, and program execution will resume on the statement
following the for block.
The following program uses a for loop to print the square
roots of the numbers between 1 and 99. Notice that in this example,
the loop control variable is called num.
int main()
int num;
double sq_root;
cout< }
return 0;
This program uses the standard function sqrt( ). As
explained in Module 2, the sqrt( ) function returns the square root of
its argument. The argument must be of type double, and the
function returns a value of type double. The header is
Another loop is the while. The general form of the while loop
is while(expression) statement; where statement may be a single
statement or a block of statements. The expression defines the
condition that controls the loop, and it can be any valid expression.
The statement is performed while the condition is true. When the
condition becomes false, program control passes to the line
immediately following the loop.
The following program illustrates this characteristic of the
while loop. It displays a line of periods. The number of periods
displayed is equal to the value entered by the user. The program
does not allow lines longer than 80 characters. The test for a
permissible number of periods is performed inside the loop’s
conditional expression, not outside of it.
using namespace std;
int main()
int len;
cout<<”Enter length(1 to 79)”;
while(len>0 $$ len<80)
return 0;
If len is out of range, then the while loop will not execute
even once. Otherwise, the loop executes until len reaches zero.
There need not be any statements at all in the body of the while
loop. Here is an example: while(rand() != 100) ; This loop iterates
until the random number generated by rand( ) equals 100.
The last of C++’s loops is the do-while. Unlike the for and the
while loops, in which the condition is tested at the top of the loop,
the do-while loop checks its condition at the bottom of the loop.
This means that a do-while loop will always execute at least once.
The general form of the do-while loop is
do { statements; } while(condition);
Although the braces are not necessary when only one
statement is present, they are often used to improve readability of
the do-while construct, thus preventing confusion with the while.
The do-while loop executes as long as the conditional expression is
The following program loops until the number 100 is entered:
using namespace std;
int main()
int num;
cout << “Enter a number (100 to stop):”;
cin>> num;
return 0;
It is possible to force an immediate exit from a loop,
bypassing the loop’s conditional test, by using the break statement.
When the break statement is encountered inside a loop, the loop is
immediately terminated, and program control resumes at the next
statement following the loop. Here is a simple example:
using namespace std;
int main()
int t;
if(t==10) break;
cout< }
return 0;
The output from the program is shown here: 0 1 2 3 4 5 6 7 8 9
As the output illustrates, this program prints only the
numbers 0 through 9 on the screen before ending. It will not go to
100, because the break statement will cause it to terminate early.
Using continue
It is possible to force an early iteration of a loop, bypassing
the loop’s normal control structure. This is accomplished using
continue. The continue statement forces the next iteration of the
loop to take place, skipping any code between itself and the
conditional expression that controls the loop.
For example, the following program prints the even numbers
between 0 and 100:
using namespace std;
int main()
int x;
if(x%2) continue;
cout< }
return 0;
Only even numbers are printed, because an odd number will
cause the continue statement to execute, resulting in early iteration
of the loop, bypassing the cout statement. Remember that the %
operator produces the remainder of an integer division. Thus, when
x is odd, the remainder is 1, which is true. When x is even, the
remainder is 0, which is false. In while and do-while loops, a
continue statement will cause control to go directly to the
conditional expression and then continue the looping process. In
the case of the for, the increment part of the loop is performed, then
the conditional expression is executed, and then the loop
The goto is C++’s unconditional jump statement. Thus, when
encountered, program flow jumps to the location specified by the
There are times when the use of the goto can clarify
program flow rather than confuse it. The goto requires a label for
operation. A label is a valid C++ identifier followed by a colon.
Furthermore, the label must be in the same function as the goto
that uses it.
For example, a loop from 1 to 100 could be written using a
goto and a label, as shown here:
if(x<100) goto loop1;
One good use for the goto is to exit from a deeply nested routine.
For example, consider the following code fragment:
if(…)goto stop
cout<<”Enter in program.\n”;
Eliminating the goto would force a number of additional tests
to be performed. A simple break statement would not work here,
because it would only cause the program to exit from the innermost
Unit Structure
4.1 Introduction :
4.2 Function
4.3 Arguments passed by value and by reference.
4.4 Default values in parameters
4.5 Overloaded functions
4.6 inline functions
4.7 Recursivity
Using functions we can structure our programs in a more
modular way, accessing all the potential that structured
programming can offer to us in C++.
A function is a group of statements that is executed when it
is called from some point of the program. The following is its format:
type name ( parameter1, parameter2, ...) { statements
 type is the data type specifier of the data returned by the
 name is the identifier by which it will be possible to call the
 parameters (as many as needed): Each parameter consists
of a data type specifier followed by an identifier, like any
regular variable declaration (for example: int x) and which
acts within the function as a regular local variable. They
allow to pass arguments to the function when it is called. The
different parameters are separated by commas.
 statements is the function's body. It is a block of statements
surrounded by braces { }.
Here you have the first function example:
// function example
using namespace std;
int addition (int a, int b)
int r;
return (r);
int main ()
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
The result is 8
In order to examine this code, first of all remember
something said at the beginning of this tutorial: a C++ program
always begins its execution by the main function. So we will begin
We can see how the main function begins by declaring the
variable z of type int. Right after that, we see a call to a function
called addition. Paying attention we will be able to see the similarity
between the structure of the call to the function and the declaration
of the function itself some code lines above:
The parameters and arguments have a clear
correspondence. Within the main function we called to addition
passing two values: 5 and 3, that correspond to the int a and int b
parameters declared for function addition.
At the point at which the function is called from within main,
the control is lost by main and passed to function addition. The
value of both arguments passed in the call (5 and 3) are copied to
the local variables int a and int b within the function.
Function addition declares another local variable (int r), and
by means of the expression r=a+b, it assigns to r the result of a
plus b. Because the actual parameters passed for a and b are 5
and 3 respectively, the result is 8.
The following line of code:
return (r);
finalizes function addition, and returns the control back to the
function that called it in the first place (in this case, main). At this
moment the program follows it regular course from the same point
at which it was interrupted by the call to addition. But additionally,
because the return statement in function addition specified a value:
the content of variable r (return (r);), which at that moment had a
value of 8. This value becomes the value of evaluating the function
So being the value returned by a function the value given to the
function call itself when it is evaluated, the variable z will be set to
the value returned by addition (5, 3), that is 8. To explain it another
way, you can imagine that the call to a function (addition (5,3)) is
literally replaced by the value it returns (8).
The following line of code in main is:
cout << "The result is " << z;
That, as you may already expect, produces the printing of the
result on the screen.
Until now, in all the functions we have seen, the arguments
passed to the functions have been passed by value. This means
that when calling a function with parameters, what we have passed
to the function were copies of their values but never the variables
For example, suppose that we called our first function
addition using the following code:
int x=5, y=3, z;
z = addition ( x , y );
What we did in this case was to call to function addition
passing the values of x and y, i.e. 5 and 3 respectively, but not the
variables x and y themselves.
This way, when the function addition is called, the value of
its local variables a and b become 5 and 3 respectively, but any
modification to either a or b within the function addition will not have
any effect in the values of x and y outside it, because variables x
and y were not themselves passed to the function, but only copies
of their values at the moment the function was called.
But there might be some cases where you need to
manipulate from inside a function the value of an external variable.
For that purpose we can use arguments passed by reference, as in
the function duplicate of the following example:
// passing parameters by reference
using namespace std;
void duplicate (int& a, int& b, int& c)
int main ()
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
The output is : x=2, y=6, z=14
The first thing that should call your attention is that in the
declaration of duplicate the type of each parameter was followed by
an ampersand sign (&). This ampersand is what specifies that their
corresponding arguments are to be passed by reference instead of
by value.
When a variable is passed by reference we are not passing
a copy of its value, but we are somehow passing the variable itself
to the function and any modification that we do to the local
variables will have an effect in their counterpart variables passed as
arguments in the call to the function.
To explain it in another way, we associate a, b and c with the
arguments passed on the function call (x, y and z) and any change
that we do on a within the function will affect the value of x outside
it. Any change that we do on b will affect y, and the same with c
and z.
That is why our program's output, that shows the values
stored in x, y and z after the call to duplicate, shows the values of
all the three variables of main doubled.
If when declaring the following function:
void duplicate (int& a, int& b, int& c)
we had declared it this way:
void duplicate (int a, int b, int c)
i.e., without the ampersand signs (&), we would have not
passed the variables by reference, but a copy of their values
instead, and therefore, the output on screen of our program would
have been the values of x, y and z without having been modified.
Passing by reference is also an effective way to allow a
function to return more than one value. For example, here is a
function that returns the previous and next numbers of the first
parameter passed.
// more than one returning value
using namespace std;
void prevnext (int x, int& prev, int& next)
prev = x-1;
next = x+1;
int main ()
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
The output is : Previous=99, Next=101
When declaring a function we can specify a default value for
each parameter. This value will be used if the corresponding
argument is left blank when calling to the function. To do that, we
simply have to use the assignment operator and a value for the
arguments in the function declaration. If a value for that parameter
is not passed when the function is called, the default value is used,
but if a value is specified this default value is ignored and the
passed value is used instead.
For example:
// default values in functions
using namespace std;
int divide (int a, int b=2)
int r;
return (r);
int main ()
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
The output is : 6
As we can see in the body of the program there are two calls
to function divide. In the first one:
divide (12)
we have only specified one argument, but the function
divide allows up to two. So the function divide has assumed that the
second parameter is 2 since that is what we have specified to
happen if this parameter was not passed (notice the function
declaration, which finishes with int b=2, not just int b). Therefore the
result of this function call is 6 (12/2).
In the second call:
divide (20,4)
there are two parameters, so the default value for b (int b=2)
is ignored and b takes the value passed as argument, that is 4,
making the result returned equal to 5 (20/4).
In C++ two different functions can have the same name if
their parameter types or number are different. That means that you
can give the same name to more than one function if they have
either a different number of parameters or different types in their
For example:
// overloaded function
using namespace std;
int operate (int a, int b)
return (a*b);
float operate (float a, float b)
return (a/b);
int main ()
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
The output is : 10
In this case we have defined two functions with the same
name, operate, but one of them accepts two parameters of type int
and the other one accepts them of type float. The compiler knows
which one to call in each case by examining the types passed as
arguments when the function is called. If it is called w

About the author