0% found this document useful (0 votes)
10 views

Object Oriented Programming Using C++ - Student guide Part A

Uploaded by

amitnarayana53
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Object Oriented Programming Using C++ - Student guide Part A

Uploaded by

amitnarayana53
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

Object-Oriented

Programming
Using C++
Student Guide
Table of Contents

Chapter 1 – Introduction to Object-Oriented Programming

Overview of Programming --------------------------------------------------- 1.3


Programs -------------------------------------------------------------------------- 1.3
Programming Languages ------------------------------------------------------ 1.4
Pseudocode ----------------------------------------------------------------------- 1.6
Programming Approaches----------------------------------------------------- 1.6
Object-Oriented Programming ---------------------------------------------- 1.8
The Foundation of Object-Orientation -------------------------------------- 1.8
Benefits of Object-Orientation ---------------------------------------------- 1.11
C++: An Object-Oriented Language -------------------------------------- 1.14
Classes in C++ ----------------------------------------------------------------- 1.14
Activity: Creating Classes in C++ ------------------------------------------ 1.17
Problem Statement------------------------------------------------------------- 1.17
Solution -------------------------------------------------------------------------- 1.17
Practice Questions ------------------------------------------------------------ 1.18
Summary ----------------------------------------------------------------------------- 1.19

Chapter 2 – Creating Objects

Variables and Data Types ---------------------------------------------------- 2.3


Rules for Naming Variables in C++ -----------------------------------------2.3
Working with Variables -------------------------------------------------------2.4
Writing and Executing a C++ Program ---------------------------------- 2.12
Components of a C++ Program --------------------------------------------- 2.12
Displaying Formatted Output ------------------------------------------------ 2.14
Introducing Functions --------------------------------------------------------- 2.15
Creating Objects --------------------------------------------------------------- 2.19
Compiling, Linking, and Executing the Program ------------------------ 2.21
Introducing Arrays ----------------------------------------------------------- 2.31
The Need for Arrays----------------------------------------------------------- 2.31
Activity: Introducing Arrays------------------------------------------------ 2.37
Problem Statement ------------------------------------------------------------- 2.37
Solution -------------------------------------------------------------------------- 2.37
Introducing Structures------------------------------------------------------- 2.39
Defining Structures ------------------------------------------------------------ 2.39
Array of Structures ------------------------------------------------------------ 2.41
Practice Questions ------------------------------------------------------------ 2.43
Summary ----------------------------------------------------------------------------- 2.44
Exercises ------------------------------------------------------------------------------ 2.45
Exercise 1 ----------------------------------------------------------------------- 2.45
Exercise 2 ----------------------------------------------------------------------- 2.45
Exercise 3 ----------------------------------------------------------------------- 2.46
Exercise 4 ----------------------------------------------------------------------- 2.46
Exercise 5 ----------------------------------------------------------------------- 2.47

Chapter 3 – Encapsulation and Abstraction

Access Specifiers --------------------------------------------------------------- 3.3


Abstraction and Encapsulation -----------------------------------------------3.3
Implementing Abstraction and Encapsulation using
Access Specifiers ---------------------------------------------------------------3.4
Static Variables and Functions ---------------------------------------------- 3.9
Static Variables ----------------------------------------------------------------- 3.9
Static Functions ---------------------------------------------------------------- 3.10
Friend Functions and Classes ----------------------------------------------- 3.12
Friend Functions --------------------------------------------------------------- 3.12
Friend Classes ------------------------------------------------------------------ 3.13
Practice Questions ------------------------------------------------------------ 3.14
Summary ----------------------------------------------------------------------------- 3.15
Exercises ----------------------------------------------------------------------------- 3.16
Exercise 1 ----------------------------------------------------------------------- 3.16

Chapter 4 – Operators and Decision-Making Constructs

Operators ----------------------------------------------------------------------------- 4.3


Arithmetic Operators ----------------------------------------------------------- 4.3
Arithmetic Assignment Operators ------------------------------------------- 4.5
Unary Operators ---------------------------------------------------------------- 4.7
Comparison Operators --------------------------------------------------------- 4.8
Logical Operators --------------------------------------------------------------- 4.9
Operator Precedence --------------------------------------------------------- 4.11
Expressions in C++ ------------------------------------------------------------ 4.12
Type Conversion --------------------------------------------------------------- 4.14
Conditional Constructs------------------------------------------------------- 4.16
The if...else Construct--------------------------------------------------------- 4.16
The switch...case Construct -------------------------------------------------- 4.20
Loop Constructs --------------------------------------------------------------- 4.23
The while Loop ---------------------------------------------------------------- 4.23
The do...while Loop ----------------------------------------------------------- 4.26
The for Loop Construct ------------------------------------------------------- 4.27
Nested Loops ------------------------------------------------------------------- 4.29
Activity: Loop Constructs --------------------------------------------------- 4.31
Problem Statement 1 ---------------------------------------------------------- 4.31
Solution -------------------------------------------------------------------------- 4.31
Problem Statement 2 ---------------------------------------------------------- 4.32
Solution -------------------------------------------------------------------------- 4.32
Problem Statement 3 ---------------------------------------------------------- 4.34
Solution -------------------------------------------------------------------------- 4.34
The Scope of a Variable------------------------------------------------------ 4.35
File Scope ----------------------------------------------------------------------- 4.35
Local Scope --------------------------------------------------------------------- 4.36
Class Scope --------------------------------------------------------------------- 4.37
Practice Questions ------------------------------------------------------------ 4.38
Summary ----------------------------------------------------------------------------- 4.39
Exercises ------------------------------------------------------------------------------ 4.40
Exercise 1 ----------------------------------------------------------------------- 4.40
Exercise 2 ----------------------------------------------------------------------- 4.40
Exercise 3 ----------------------------------------------------------------------- 4.41
Additional Exercises ---------------------------------------------------------- 4.42

Chapter 5 – More About Functions

Using Built-In Functions------------------------------------------------------ 5.3


Character Functions ------------------------------------------------------------5.3
String Functions -----------------------------------------------------------------5.5
Numeric Functions--------------------------------------------------------------5.8
Command Line Parameters ------------------------------------------------- 5.11
Declaration of Functions------------------------------------------------------ 5.12
Activity: Command Line Parameters ------------------------------------- 5.13
Problem Statement ------------------------------------------------------------- 5.13
Solution -------------------------------------------------------------------------- 5.13
Practice Questions ------------------------------------------------------------ 5.14
Summary ----------------------------------------------------------------------------- 5.15
Exercises ------------------------------------------------------------------------------ 5.16
Exercise 1 ----------------------------------------------------------------------- 5.16
Exercise 2 ----------------------------------------------------------------------- 5.16

Chapter 6 – Constructors and Destructors

Initializing Objects ------------------------------------------------------------ 6.3


The Need for Constructors ----------------------------------------------------6.3
The Need for Destructors ------------------------------------------------------6.6
The Life Cycle of an Object --------------------------------------------------6.7
Scope Resolution Operator----------------------------------------------------6.8
Constructors with Parameters------------------------------------------------ 6.10
Using Pointers ----------------------------------------------------------------- 6.11
Call by Value ------------------------------------------------------------------- 6.14
Call by Reference -------------------------------------------------------------- 6.17
Returning Pointers from Functions ----------------------------------------- 6.23
Pointers and Arrays ----------------------------------------------------------- 6.24
Pointers to Structures --------------------------------------------------------- 6.27
Practice Questions ------------------------------------------------------------ 6.33
Summary ----------------------------------------------------------------------------- 6.35
Exercises ----------------------------------------------------------------------------- 6.36
Exercise 1 ----------------------------------------------------------------------- 6.36
Exercise 2 ----------------------------------------------------------------------- 6.36

Chapter 7 – Polymorphism

Introducing Polymorphism--------------------------------------------------- 7.3


Function Overloading --------------------------------------------------------- 7.4
Function Signature-------------------------------------------------------------- 7.5
Constructor Overloading ------------------------------------------------------ 7.5
Operator Overloading --------------------------------------------------------- 7.8
Need for Operator Overloading ---------------------------------------------- 7.8
Overloading Unary Operators ---------------------------------------------- 7.12
Simple Prefix Unary Operators --------------------------------------------- 7.12
Pre and Post Increment and Decrement Operators----------------------- 7.13
Overloading Binary Operators --------------------------------------------- 7.16
Practice Questions ------------------------------------------------------------ 7.18
Summary ----------------------------------------------------------------------------- 7.19
Exercises ----------------------------------------------------------------------------- 7.20
Exercise 1 ----------------------------------------------------------------------- 7.20
Exercise 2 ----------------------------------------------------------------------- 7.21
Additional Exercises ---------------------------------------------------------- 7.23

Chapter 8 – Inheritance

Introducing Inheritance------------------------------------------------------- 8.3


Superclass and Subclass ------------------------------------------------------- 8.4
Types of Inheritance------------------------------------------------------------ 8.5
Generalization -------------------------------------------------------------------- 8.8
Implementing Inheritance--------------------------------------------------- 8.10
Determining Inheritance Hierarchies -------------------------------------- 8.10
Sequence of Invoking Constructors and Destructors ------------------- 8.11
Base Class Initialization ------------------------------------------------------ 8.12
Access Specifiers of Derivation--------------------------------------------- 8.14
Activity: Implementing Inheritance --------------------------------------- 8.17
Problem Statement------------------------------------------------------------- 8.17
Solution -------------------------------------------------------------------------- 8.17
Practice Questions ------------------------------------------------------------ 8.19
Summary ----------------------------------------------------------------------- 8.20
Exercises ----------------------------------------------------------------------- 8.21
Exercise 1 ----------------------------------------------------------------------- 8.21

Solutions to Practice Questions

Solutions to Practice Questions ----------------------------------------------S.1


Chapter 1 ---------------------------------------------------------------------S.1
Chapter 2 ---------------------------------------------------------------------S.1
Chapter 3 ---------------------------------------------------------------------S.2
Chapter 4 ---------------------------------------------------------------------S.4
Chapter 5 ---------------------------------------------------------------------S.5
Chapter 6 ---------------------------------------------------------------------S.5
Chapter 7 ---------------------------------------------------------------------S.5
Chapter 8 ---------------------------------------------------------------------S.6

Glossary

Glossary-------------------------------------------------------------------------- G.
Chapter 1
Object-Oriented Programming (OOP) is one of the most popular methodologies in
software development. It offers a powerful model for creating computer programs. It
speeds up the program development process, improves maintenance, and enhances
reusability of programs.

This chapter introduces the basic concepts of programming. It also discusses


the basics of object-oriented programming. In addition, it introduces C++ as
an object-oriented language.

Objectives

In this chapter, you will learn to:


 Understand the concept of programming
 Understand object-oriented programming
 Understand C++ as an object-oriented language
Overview of Programming
You might have noticed computers being used at airline reservation counters, shops,
restaurants, and various other locations. At each of these places, a user enters some values
in the computer and the computer generates an output, which is either displayed on the
computer screen or printed on paper. Let us consider the example of an airline reservation
counter. When you want a seat reserved on a particular flight, you provide information
about your requirements such as destination, date and time of your departure and the class
in which booking is required. The clerk at the reservation counter enters this information
into a computer. Details regarding the availability of tickets are then displayed on the
screen.

Computer follows an Input-Process-Output cycle. It needs set of instructions called


program to specify the input required, process to be followed, and the output required.

Program is written in a specific language called programming language, so that computer


can understand the instructions.

Programs

How does a computer know what are the steps to be followed to process reservation
requests? How does it manage to calculate your shopping bills at the local store? How
does it generate your report card at school? Is it an all-knowing machine? Do you have to
buy a different computer for each of these above-mentioned activities? The answer to the
last two questions is ‘No’. It is not an all-knowing machine and you do not require a
separate computer for each of these activities.

Then, how does a computer function? A computer is designed to accept input, process it,
and generate output. However, it has to be provided with a set of instructions that state:
 The kind of input that will be provided. For example, in the case of reservation
requests, flight date, flight time, class, and destination will be some of the inputs.
 The processing that needs to be done. For example, accepting the values, checking
for availability of seats, and validating accepted values.
 The kind of output expected. For example, the seat availability status.

A set of instructions to perform a particular job is called a program. Therefore, for each
job that you want the computer to perform, you require a separate program. Instructions in
a program can be:
 Sequential: Instructions that are executed one after the other.
 Decision Making: Instructions that evaluate an expression (relation or condition)
first and then, depending upon whether the value of the expression is 'true' (non-zero)
or 'false' (zero), it transfers the control to a particular statement.
 Iterative: Instructions that are executed repeatedly, depending on the value of an
expression (relation or condition).

Any real-life problem will consist of a number of small jobs. Therefore, to solve a
real-life problem, you have a number of programs that together form an application. For
example, a payroll application for processing employee compensation details and
generating paychecks and associated reports might have two programs:
 Program to generate paychecks
 Program to print reports

Programming Languages

A computer is made up of a number of electronic circuits. An electronic circuit can be


either in an on state or an off state. Therefore, the components of a computer are
represented as a combination of on and off states. The on state is represented by ‘1’ and
the off state by ‘0’. This implies that a computer can understand only 0s and 1s.
Therefore, any instruction given to a computer must be a sequence of 0s and 1s.

A sequence of 0s and 1s can be used to describe any physical operation that the computer
performs. Therefore, a computer system uses a number system that consists of only two
digits, 0 and 1. This language that the computer understands is called the machine
language. For example, the machine language for a particular computer could have the
instruction set, as shown in the following table.

Command Machine Code

ADD 00000001

SUBTRACT 00000010

MULTIPLY 00000100

DIVIDE 00001000

READ FROM KEYBOARD 00010000

WRITE ON SCREEN 00100000

WRITE ON PRINTER 01000000

Instruction Set
It is certainly difficult for anybody to remember instructions in the form of 0s and 1s.
Therefore, we use high-level programming languages to write programs. A high-level
programming language consists of a set of instructions, which are represented using
simple English words. So, when you want the computer to display the output on the
screen, you type the instruction ‘WRITE ON SCREEN’ and not ‘00100000’.

There are many high-level programming languages available, such as C, C++, and Java.
Each language has its own advantages. You need to evaluate the problem at hand before
deciding on the programming language to use.

All languages have a vocabulary, which is a list of words that have a specific meaning in
that language. Languages also have their own grammar rules, which state the rules for
combining words to form sentences. This is what ensures that whatever is spoken in a
particular language is interpreted similarly by all people who understand the language.
Similarly, programming languages also have a vocabulary, which is referred to as the set
of keywords of that language, and a grammar, which is referred to as the syntax.

As stated earlier, a program written in any programming language is a set of logically


related instructions. These instructions have two parts, as shown in the following figure.

Format of a Programming Language Instruction

The two parts of a programming language instruction are:


 Operation code (opcode): This part instructs a computer about the operation to be
performed.
 Operand: This part instructs the computer about the location of the data on which
the operation specified by the opcode is to be performed.

For example, in the instruction Add A and B, Add is the opcode and A and B are
operands.

Before we actually start writing a program we need to derive a procedure for solving the
problem. An algorithm is a sequence of steps required to solve a problem.
Programming Approaches

There are a number of programming approaches that you can follow to create a program
or an application. Each approach has evolved as a result of certain limitations of its
previously prevalent approaches. The main reason for development of newer
programming approaches (techniques) over a period of time is to effectively handle the
increasing complexity of programs and to easily maintain code.

Some of the common programming approaches are:


 Sequential approach
 Modular approach
 Object-oriented approach

Sequential Approach
The sequential approach includes programs that are actually a list of instructions to the
system to perform a specific task. Each statement in a program is a command to be
processed by the system.

The limitation with this approach is that with an increase in the number of instructions,
the program becomes too lengthy and complicated to understand. As a result, the
maintenance overhead increases to a large extent. In addition, the programming effort
increases manifolds in a large program where each statement is an instruction to the
system.
Modular Approach
The modular approach was introduced to overcome the limitations of the sequential
approach. Since long programs are difficult to manage and maintain, the modular
approach divides the programs into entities known as functions. A function is a group of
statements that perform a specific task. Further, these functions are clubbed together in
logical groups with each group containing interrelated functions. Such logical groups are
known as modules.

In the modular approach, many modules/functions access the same set of data. Therefore,
a change in the type or location of data requires a change in all the functions that access
the data. This is quite tedious in programs with a large number of functions. Another
limitation of the modular approach is that it does not portray the real world and entities in
the programs. For example, in an inventory management application, more emphasis will
be on purchase-and-issue-related activities rather than on the inventory itself.
Object-Oriented Approach
Object-oriented approach is the latest of the programming approaches and portrays the
real world in the programs. The approach treats each entity as an object which has
well-defined state, behavior, and unique identity. The approach hides unnecessary details
from the users and allows creation of programs that are easy to manage and maintain.
Object-Oriented Programming
Object-Oriented Programming (OOP) is one of the most popular methodologies in
software development. It offers a powerful model for creating computer programs. It
speeds the program development process, improves maintenance, and enhances
reusability of programs.

The Foundation of Object-Orientation

People have often asked why software cannot be constructed the way an aircraft or a
high-rise building is constructed – by putting together several small constituent
components to build the whole. Software can be developed by first breaking the
application into its component objects, which interact with each other, and using these to
build the software. Thus, what is required is an object-oriented approach to the building of
software.

The basic concepts of object orientation are contained in the object model. The object
model furnishes the conceptual framework on which the object-oriented methods are
based. We will discuss the basic concepts specified in the object model in the following
pages.

Objects
An object is one of the first things that an infant learns to recognize just as it learns to
recognize its parents.

As the infant grows older, it learns to recognize an object, such as a clock, book, or a tape
recorder, as not only having a definite, distinct boundary, but also as one that has a unique
identity, quite apart from the other objects surrounding it.

The dictionary defines an object as a ‘material thing that is capable of being presented to
the senses’. For our purpose, a simple definition of an object would be a ‘tangible entity
that may exhibit some well-defined behavior’. Consider the following example of a tennis
ball:
 A tennis ball is a tangible, visible entity, which has a visible boundary.
 A tennis ball has a specific purpose.
 You can direct a specific action towards a tennis ball (hit it with a racquet and send it
flying).
But let us not limit our definition of an object to merely ‘something that can be seen, held
and touched’, such as a tennis ball, an automobile, or an armchair. For the purpose of
software development, the idea of the object needs refinement. For example, consider the
Acme Nut and Bolt Company. An organization, you will argue, does not have a visible
boundary, unlike a tennis ball or a tape-recorder. True, but while it does not possess a
physical boundary, it does have a conceptual boundary. Like all organizations, it has a
specific purpose, and one can direct a specific action towards it (just ask the customers
and shareholders). Thus, by our definition, the Acme Nut and Bolt Company is an object.

State, Behavior, and Identity of an Object

According to Grady Booch, an object has the following characteristics:


 It has a state.
 It may display a behavior.
 It has a unique identity.

For example, you can take a car as an object. It can have states such as moving and
stationary. It can accelerate, decelerate, turn right, or turn left, which is its behavior. The
car also has an identity, such as a unique registration number. The following figures
depict the characteristics of a car.

State: Behavior: Identity: Registration


Stationary Accelerate Number (XY245)

An Object has State, Behavior, and Identity

The state of an object is indicated by a set of attributes and the values of these attributes.
Thus, a chemical can be characterized by temperature, pressure, or density and the values
of each of these. The behavior refers to the change of these attributes over a period of
time.

Objects do not exist in isolation. They interact with other objects, and react to these
interactions. These interactions take place through messages. Grady Booch has defined
behavior as follows:

“Behavior is how an object acts and reacts, in terms of its state changes and message
passing.”
That explains the first part of the definition of an object “An object has state, exhibits
some well-defined behavior…”. Now, let us examine the next part of the
definition -“ … and has a unique identity.”

Each object has a unique identity, just as each person has a unique identity. The identity
of an object distinguishes it from all other objects. In the case of the pay-phone described
here, its identity will be its serial number assigned by the manufacturer. Two objects may
have the same behavior, may or may not have the same state, and will never have the
same identity. The identity of an object never changes in its lifetime. Thus, two tennis
balls may have the same color, be made of the same material, have the same weight and
the same circumference and display the same behavior, but will still have distinct
identities (say one ball has the factory seal number ‘A189735’ and the other ‘S660794’).

Classes
Look at the world around you. It is full of objects. Objects of different shapes, sizes and
colors; objects stationary and mobile; objects that exist in this world for different
purposes. If we were to deal with this vast number and variety of objects simultaneously,
we will be at a loss. We can only do what the zoologists do. The earth is inhabited by
millions of animals. A zoologist cannot do any meaningful study of these objects without
organizing this vast variety of animals found in the world in a logical manner. Thus,
zoologists have classified animals into their kingdom, genus, family, and species.

Similarly, the millions of objects that we see in this world can be classified on the basis of
common attributes that they possess. Let us take a simple example from the animal world.
The peacock, the sparrow, and the kingfisher are all called Birds. Why? All of them share
some common characteristics. All three have properties that are common to the family of
Birds. For example, all of them lay eggs and hatch their young; all of them are covered
with feathers, have hollow bone structures, and have the ability to fly. Thus, we can say
that the peacock, the sparrow and the kingfisher all share structural and behavioral
similarities and belong to the class called Birds, as shown in the following figure.

Birds

Peacock Sparrow Kingfisher

The Birds class

From the above example, we can define a class as ‘a set of objects that share structure and
a common behavior’.
We started off by saying that the world around us is full of objects. Making a conscious
attempt to identify the objects around you and classifying them into classes can be fun.
And (this is important from the point of view of software development), it can be equally
exciting to identify objects and classes in a given situation or situations. When we watch a
play in a theatre, we recognize the fact that there is a group of actors on the stage and each
actor is playing his/her own part. Similarly, in a given situation we can identify a group of
objects that play a part. The one difference here is that ‘objects’ include animate (living) as
well as inanimate objects. Thus, on the stage you can identify Professor Henry Higgins,
Col. Pickering and Eliza Doolittle, and the armchairs, the fireplace, or the portrait on the
wall.

Messages and Methods


A message is transmitted by one object to another. A message is a request for an action to
be taken, and is accompanied by additional information needed to carry out the request.

Benefits of Object-Orientation

Why do we opt for the object-oriented approach? Some of the principal reasons are:
Realistic modeling, Reusability, and Resilience to change.

Realistic Modeling
Since we live in a world of objects, it logically follows that the object-oriented approach
models the real world more accurately.

Reusability
In the software industry, as in other industries, a large portion of time and energy is spent
in recreating the proverbial wheel. In the object-oriented approach, you build classes,
which can be used by several applications. Consider the following analogy.

Curlcare is a brand of shampoo sold in the European market. In spite of high investments
in advertising, the management at Curlcare felt that the shampoo did not really have an
identity of its own in a market that is infested with hundreds of brands of shampoo.
Therefore, the Marketing Division came up with a strategy to project a new image for
Curlcare. Curlcare was originally available in plastic bottles, just like all other brands of
shampoo. The idea conceived by the Marketing Division was to give the shampoo a new
look by packaging it in a soft-squeeze tube.

The Design Department of the Manufacturing Division designed the tube. This design
was created on a computer, and three-dimensional (3-D) views of the tube were made.
The Packaging Division used these images to check how the tubes would appear on
shelves in the shops, and how many would fit on a standard sized shelf. The Advertising
Division used these images to figure out the new advertising strategy, and how the tube
would look in the advertisement layout. The Finance Division needed to work out the cost
of manufacturing.

All these divisions can be viewed as several teams working on one project. All the teams
used the same information about the new tube to arrive at a complete solution for
Curlcare.

The scenario at Curlcare depicts the concept of reusability that is supported by the
object-oriented approach. In object-oriented terms, the tube is a class that can be used by
all the users who need it. In the object-oriented approach, classes are designed such that
they can be reused in several systems.

Now if we extend the above scenario to include a situation where Curlcare is diversifying
into new products, say toothpaste, the work done on the design of the tube of shampoo
can be used for the tube of toothpaste. Not only are the attributes of the tube, such as
length or radius being reused, but also the methods. For example, the method used by the
Finance Department to compute the manufacturing cost of the tube of shampoo can be
used for this new product.

The benefit of reusability translates to savings in time and effort, which in turn results in
cost benefits.

Resilience to Change
Through the object-oriented approach, systems can be allowed to evolve. When a change
is suggested, the old system need not be completely abandoned and re-built from scratch.
Consider the example of Joytoys, a company that manufactures toys for children in the
age group of 1-12. The payroll system of this company has been developed using
object-oriented techniques. The company has several employees, some of whom work in
the Design Department. These designers develop new toys every season. For the past
couple of years, the company has had no cause to complain about the payroll system.

However, new developments in the company have rendered the old payroll system
inadequate. In order to keep up with competition, the company realized the need to
employ more designers. Design work is done only in certain months of the year.
Therefore, the company has now employed freelance product designers who work in the
capacity of temporary employees.
The original payroll system was designed for employees of two kinds—confirmed
employees and trainees. Though there are many attributes that are common between
confirmed employees and trainees, like name and address, there are some attributes that
are different. For example, a confirmed employee receives basic pay while a trainee
receives a stipend.

The company now wants the system to be modified to accommodate freelancers as well.
In the object-oriented system, this change does not require the entire payroll system to be
revamped. A new class of freelancers needs to be introduced to take care of all activities
related to freelancers. The rest of the system remains unchanged.

Resilience to change results in the benefit of easier maintenance. For the same reason,
even during construction, parts of the system under development can be refined without
any major change in other parts.

Existence as Different Forms


By using the object-oriented approach, objects can be made to respond differently to the
same message. The response is decided based on the information or parameters provided
with the message.

Note
Information is passed as parameters in a function. You will learn more about functions
in subsequent chapters.

If a car collides against an object, the behavior of the car after the collision will depend on
the speed of the car and nature of the object that hit the car. For example, if the car collides
with another car at high speed, both the cars will be smashed and the drivers might
get injured. On the other hand, if a car collides with a street light at a slow speed, the
impact would be less. This ability to react differently based on the information associated
with the message is known as polymorphism.
C++: An Object-Oriented Language
In the early 1980s, Bjarne Stroustrup working for Bell Labs developed the C++ language.
In his own words, "C++ was designed primarily so that my friends and I would not have
to program in assembly, C, or various modern high-level languages. Its main purpose was
to make writing good programs easier and more pleasant for the individual programmer."
(Bjarne Stroustrup, The C++ Programming Language, Third Edition. Reading, MA:
Addition-Wesley Publishing Company, 1997).

C++ was originally known as 'C with classes' as two languages contributed to its
design – C, which provided low-level features, and Simula67, which provided the class
concept. C++ is an example of an object-oriented language. Other object-oriented
languages include Java and Smalltalk.

Classes in C++

After a class is created, you can use it without knowing the specifics of how it works or
even how a class is built.

Consider the following snippet, which contains a class:


class Car
{
public:
void honk()
{
cout<<"BEEP BEEP!";
}
};

The above class declaration provides the honk() method that will display the message
“BEEP BEEP!” on your screen.

The class Keyword


The class keyword is used to declare a class. The braces are used to indicate the start and
end of a class body. A semicolon is used to end the class declaration, as shown in the
following code snippet:
class Car
{
...
};
The Class Name
The class keyword is followed by the name of the class. In the above example, Car is
class name. When you create classes, you must consider the following naming
conventions and rules.

Class Naming Conventions in C++

Class names should follow certain naming conventions or guidelines. These are:
1. A class name should be meaningful [strongly recommended].
2. A class name should ideally be a noun.
3. The first letter of every word in a class name should be a capital if the class name
contains more than one word and does not use underscores. For example, for a class
related to employees, the class name can be Employee. A class name to describe
employee dependents can be EmployeeDependent.

Rules for Naming Classes in C++

Some rules for naming classes are:


1. The name of a class must not contain any embedded space or symbol like ? - + ! @ #
% ^ & * ( ) [ ] { } . , ; : " ' / and \. However, an underscore (‘_’) can be used wherever
a space is required.
2. A class name must begin with a letter, which may be followed by a sequence of
letters or digits (0-9) or ‘_’. The first character in a class name cannot be a digit.
3. A keyword cannot be used for a class name. For example, you cannot declare a class
called switch.

Member Functions
As discussed earlier, objects interact with each other by passing messages and responding
to them. Objects use methods to pass messages. In C++, the task of passing messages can
be accomplished by using member functions.

A function is a set of statements that performs a specific task in response to a message.


The functions of an object are called the member functions in C++. Member functions are
declared inside the class body. The function declaration introduces the function in the
class and the function definition contains the function code.

Introduction to Object-Oriented Programming 1.15


Consider the following code snippet:
class Car
{
void honk();
};

The above code shows an example of a member function named, honk(), declared inside
the class. The declaration of a function is also called the prototype of the function.

Consider the following code snippet:


class Car
{
void honk()
{
cout<<"BEEP BEEP!"<<endl;
}
};

The above code shows an example of a member function named, honk(), declared and
defined inside the class. Notice that the function definition contains the code, which is
enclosed in a block. The block is enclosed within braces '{}'.

Note
The cout operator is used to display output on the screen.

Note
The endl manipulator is a command that takes the cursor to the new line.
Activity: Creating Classes in C++

Problem Statement
As a member of a team that is developing the billing system software for Diaz
Telecommunications, Inc., you have been assigned the task of creating a software module
that accepts and displays customer details. Declare the Customer class and the member
functions. The member function that accepts customer details should display the message
“Accepting Customer Details”. Similarly, the member function to display customer details
on the screen should display the message “Displaying Customer Details”.

Solution
class Customer
{
void accept()
{
cout << “Accepting Customer Details” << endl;
}
void display()
{
cout << “Displaying Customer Details” << endl;
}
};

Practice Questions

1. As a member of a team that is developing an automated booking system for the


Railways, you have been assigned the task of creating a module that accepts the
details of a passenger and checks whether the ticket has been confirmed or is in the
waiting list. The module then prints the list of confirmed passengers. Declare a
Ticket class that consists three member functions, booking(), status(), and
print().
Summary
In this chapter, you learned that:
 Program is written in a specific language called programming language, so that
computer can understand the instructions.
 The object-oriented approach views the systems as consisting of component objects
and looks at the interactions between them.
 An object is an entity that may have a physical boundary and is also characterized
by:
 State
 Behavior
 Identity
 A class consists of a set of objects that share a common structure and behavior.
 If one object desires an action from another object, it sends a message to the second
object.
 The object that receives the message is called the receiver; the set of actions taken by
the receiver constitutes the method.
 The benefits of the object-oriented approach are:
 Realistic modeling, hence it is easier to use
 Reusability of code, hence it saves time and cost
 Resilience to change, hence systems are easier to maintain
 Existence in different forms, hence it allows objects to respond differently to the
same message
 Bjarne Stroustrup developed the C++ language in the early 1980s.
ng Objects

CHAPTER 2

A class is a blueprint for an entity. To use this blueprint in a program, you need to
create an instance of the class. An instance of a class is known as an object. It
provides access to the member variables and member functions of a class.

This chapter discusses how to declare variables, and write and execute C++ programs. It
also discusses how to use arrays and structures in C++ programs.

Objectives

In this chapter, you will learn to:


 Use variables in C++ programs
 Write and execute C++ programs
 Use arrays in C++ programs
 Use structures in C++ programs

2.2 Creating Objects


Variables and Data Types
A variable is a location in memory that has a name and may contain a value. The value
can be an integer value like 27, a decimal value like 9.85, or a character value like 'L'. A
program refers to a variable using its name. Certain rules and conventions govern the
naming of variables.

Rules for Naming Variables in C++

The following list provides the set of rules for naming variables in C++:
 Variable names should not have any embedded spaces or symbols such as ? ! @ #
+ - % ^ & * ( ) [ ] { } . , ; : " ' / and \. However, underscores (‘_’) can
be used wherever a space is required, for example basic_salary.
 Variable names must be unique. For example, to store four different numbers, four
unique variable names need to be used. Uppercase letters are considered distinct
from lowercase letters.
 A variable name must begin with a letter or an underscore, which may be followed
by a sequence of letters, digits (0-9), or underscores. The first character in a variable
name cannot be a digit.
 Keywords cannot be used as variable names. For example, you cannot declare a
variable named class, since it is a keyword in C++.

Note
A set of valid characters representing letters, digits, or any other symbols that are
recognized by C++ is known as its character set.

The following examples are some valid variable names in C++:


 address1
 employee_name
 basic_salary
 this_variable_name_is_very_long

The following examples are some invalid variable names in C++:


 #phone
 1stName

Creating Objects 2.3


Note
C++ is a case-sensitive language. This means that the variable, customerName, is not
the same as the variable, customername.

Working with Variables

A variable must be declared by specifying its data type. A data type defines the type of
data that can be stored in a variable. For example, a variable called name will ideally store
characters; whereas, a variable called salary will store numbers.

Built-in Data Types in C++


Built-in data types are data types at the lowest level, that is, those used for actual data
representation in memory.

The built-in data types are:


 char: For characters and strings
 int: For integers
 float and double: For numbers with decimals (For example, amounts, quotients,
etc.)

Since the above data types are represented at the machine level, the storage requirement is
hardware dependant. The following table shows the storage requirements for the built-in
data types.

Data Number of Bytes on a Minimum Value Maximum


Type 32-bit Computer Value

char 1 -128 127

int 2 or 4 -2^31 (2^31)-1

float 4 3.4 X 10-38 3.4 X 1038 -1

double 8 1.7 X 10-308 1.7 X 10308 -1

Storage Requirements of Built-in Data Types

2.4 Creating Objects


Type Modifiers
You can modify the default range of the built-in data types. To achieve this, C++ provides
you with the following type modifiers:
 long
 short
 signed
 unsigned

Integer Type Modifiers

You can apply the preceding type modifiers to int data types. For example, you can
prefix an int declaration with the short modifier, as shown in the following statement:
short int num;

The size of a short int is two bytes. If you know that the size of the variables in your
program will be smaller than what an int can store, you can declare the variables as short.
This allows you to save system memory.

Similarly, you can apply long to int to increase the range of the int variable.

In addition to using short and long, you can modify the range of integers by qualifying
them as signed or unsigned. short, int, and long are signed by default. In other words,
they allow storing of negative values in their corresponding variables by default.
However, if you do not want to allow a variable to hold a negative value, you can declare
it as an unsigned variable.

Note
You can use only the short keyword instead of using short int as it is a short name
for the same.

Further, qualifying a data type as unsigned also modifies the range of the data type. For
example, if a signed integer has the range, -32768 to 32767 then an unsigned integer will
have the range, 0 to 65535. Declaring an integer as unsigned allows you to store higher
values in the variable than those that can be stored in a signed variable. You can use the
unsigned modifier when you know that there are no negative values to be stored. For
example, you can declare unsigned integers for storing population count, cricket scores, or
stock prices. You can use unsigned modifier as shown in the following statement:
unsigned int score;

Creating Objects 2.5


Character Type Modifiers

The char variable is capable of storing various values, such as letters, digits, or symbols.
You can declare char data types as signed or unsigned. There is no default signed or
unsigned qualification for the char data types. The internal implementation depends on the
compiler and the type of hardware available.

A char data type allows you to store data from a range of 256 characters. As discussed
earlier, a signed data type allows you to store negative values. Similar to integers, the
char data types are also stored as integers in the memory. In other words, it is not the
actual character or symbol but its equivalent code that is stored in the memory.

Therefore, the range of a signed char data type is -128 to 127, whereas, the range of an
unsigned char data type is 0 to 255.

Member Variables
We have discussed earlier that objects have attributes or properties. For example, a car
has attributes, such as its color, model, and price. You can implement attributes in C++ by
using member variables. Member variables are declared inside the class body.

A variable can be declared by using the following syntax:


type name;

In the preceding syntax, name represents the name (identifier) of the variable that you
want to create and type represents the data type of the variable that you are creating.

The following code shows an example of a member variable declared inside the class:
class Car
{
float price;
};

In the above example, the variable price of type float is declared inside the class. You
can assign a value to a variable during compile time. Assigning a value to a variable is
referred to as initialization of the variable. Consider the following statements:
int price;
price = 150;

In the preceding statements, first a variable price is declared, and then is initialized with
the value 150. You can also declare and initialize a variable in the same statement.

For example, the preceding statements can be written as:


int price = 150;

2.6 Creating Objects


You may also use the following form of variable initialization:
int price(150);

There may be times when you have more than one variable of the same type that requires
initialization. In such a situation, you can declare and initialize multiple variables in the
same line, as shown in the following statement:
double loan = 1015.70 , interest = 0.5;

In addition to initializing variables during compile time, you can initialize the variables
during run time by accepting values from the users and assigning those values to the
corresponding variables.

Accepting and Storing Values in Member Variables

Consider the following code snippet:


class Car
{
float price;

public:

void acceptprice()
{
cout << “Enter Price :”;
cin >> price;
}
};

In C++, the cout object is used to display an output on the screen and the cin object is
used to accept and store input from the user. The cout object uses the <<output operator
to display the output on the screen. Similarly, the cin object uses the >> input operator to
accept input from the users. In the preceding code, the cout object is used to display the
text “Enter Price” on the screen and the cin object is used to accept the input provided by
the user and to store it in the price member variable.

The cout object is an instance of a predefined class named ostream, which is associated
with the standard output device. Similarly, the cin object is an instance of a predefined
class named istream, which is associated with the input device. In the case of the above
code, the message Enter Price is displayed. The cursor blinks on the screen and waits
for the user to enter data in the variable named price.

Creating Objects 2.7


Cascading of I/O Operators
In the preceding program, only one output operator (<<) has been used in one statement
(cout<< “Enter Price :” ;). However, you can use multiple output operators in the
same statement. This allows you to reduce code lines and increase readability. Consider
the following statements:
cout << “The result of 11 X 11 is : ” ;
cout << 11 * 11;

The preceding statements can be rewritten in a single statement by concatenating the


statement. The concatenation can be done by using multiple output operators, as shown in
the following statement:
cout<< “The result of 11 X 11 is : ” << 11 * 11;

Both the preceding statements generate the following result:


The result of 11 X 11 is : 121

Similar to using multiple output operators, you can use multiple input operators (>>) in
the same statement. Consider that you have multiple variables that require input from the
user. One way to accept input for the variables is to use multiple cin statements, as shown
in the following code snippet:
int English_score, Math_score, Science_score;
cout << “ Enter English, Math, and Science Scores : ” ;
cin >> English_score;
cin >> Math_score;
cin >> Science_score;

The preceding statements are quite tedious to write and are more prone to
typographical/syntactical errors. However, you can reduce the number of statements by
performing multiple input operations in the same statement. You can achieve this by
using multiple input operators in the same statement, as shown in the following code
snippet:
int English_score, Math_score, Science_score;
cout << “ Enter English, Math, and Science Scores : ” ;
cin >> English_score >> Math_score >> Science_score;

The use of multiple output or input operators in a single statement is referred to as


cascading of I/O operators and the operator that is used multiple times is known as a
cascading operator.

2.8 Creating Objects


Note
The smallest element of a program understandable by the C++ compiler is known as a
token. C++ includes the following tokens:
 Keywords: Are the reserved words used to communicate special meaning to the
language compiler.
 Identifiers: Are words used to identify the various parts of a program, such as
variables, objects, and classes. The first character of an identifier must be a letter
or an underscore( _ ). For example, MyTest or _MyObject.
 Literals: Are data items whose values remain constant during a program execution.
 Punctuators: Are characters used as separators in a program. For example,
symbols such as []. (), {}, ; and *.
 Operators: Are entities that cause certain evaluations to occur in a program.

Constants in C++
Literals are data items whose values do not change during the execution of a program.
Such data items are also called as constants. C++ includes the following constants
(literals):
 Integer constants
 Character constants
 Floating constants
 String literals

Integer Constants

Numbers that do not have any fractional part are known as integer constants. They are
whole numbers having at least one digit and no decimal point. Integer constants may be
signed or unsigned. Some valid examples of integer constants are:
 5
 +45
 -100

Note
An integer constant does not include a comma. Therefore, the value 1,000 will not be
considered as an integer constant.

Creating Objects 2.9


Character Constants

Characters enclosed within single quotes are known as character constants. Such
constants are of char type. Some valid examples of character constants are:
 ‘A’
 ‘s’
 ‘N’
 ‘5’

C++ also includes certain character constants that cannot be displayed directly on the
screen by using the keyboard. For example, you cannot display a carriage return,
backspace, or a backslash directly from the keyboard. To display such a constant, you
need to use an escape sequence, which is represented by a backslash (\) symbol followed
by the constant. Some of the commonly used escape sequences and their corresponding
character constants are provided in the following table.

Escape Sequence Character Constant

\t Horizontal Tab

\b Backspace

\\ Backslash

\’ Single quote

\” Double quote

\n Newline

\a Audible bell

Some Common Escape Sequences

Floating Constants

Numbers that have a fractional part are known as floating constants. Floating constants
can be represented in either of the following forms:
 Fractional form: This form represents real numbers having a decimal point between
digits. For example, 1.44, 3.14, or -92.7 are floating constants represented in the
fractional form.

2.10 Creating Objects


 Exponential form: This form represents real numbers in two parts, mantissa and
exponent. For example, the real number 3.8 × 103 has 3.8 as mantissa and 3 as
exponent to the base 10. This exponential form is represented as 3.8E03 by
compilers, where the number before E is the mantissa and the number after E is the
exponent.

String Literals

Multiple characters enclosed within double quotes are known as string literals. String
literals are character arrays, wherein, each character can be manipulated individually.
When a string literal is stored, an additional character, \0, is concatenated to the literal.
This special character is used to notify the compiler about the end of the literal.

Addition of the terminator character results in an increase in the size of the literal by 1.
For example, consider that you need to store the name “Jim”, which is of size 3. The
actual literal that will be stored in the memory will be “Jim\0”, whose size is now 4. This
means that the size of the stored literal includes the number of characters plus 1. Some
examples of valid string literals are:
 “Jim\’s Songs”
 “Black Sabbath”
 “nirvana”

The const Keyword


You can define a constant by using the const keyword. The const keyword is an access
modifier that sets the access property of a variable as read-only. In other words, declaring
a variable with the const keyword ensures that the value of the variable does not change
during runtime. Consider the following statement:
float Pi = 3.14;
In the preceding statement, the variable Pi is initialized with the value of 3.14. However,
this value can be changed to any value during program execution, thereby defeating the
purpose of using the standard value of Pi(π) for making arithmetic calculations. Now,
consider the following statement:
const float Pi = 3.14;

In the preceding statement, the variable Pi is initialized with the value of 3.14. However,
this time the value of Pi cannot be changed to any other value during program execution.
This is because the variable has been created as a constant variable making it a readable
variable only.

Creating Objects 2.11


Writing and Executing a C++ Program
Apart from classes and objects, a C++ program also contains others components, such as
the header files and the main() function.

Components of a C++ Program

The iostream Header File


The first statement in a typical C++ program will be:
#include<iostream.h>

This statement is called a preprocessor directive. Preprocessor directives are the


statements that are processed before the program is compiled. Compilation is the process
of converting program code to object code.

The software that handles the preprocessor directives is called a preprocessor. The
preprocessor directive shown above includes the code of the header file iostream.h into
the program. The header files contain definitions of functions, classes, and predefined
objects like cout and cin. The header files are in the include folder. Incidentally,
header file names have traditionally had the extension .h. However, this is not a
requirement for the C++ standards.

Note
The statement #include <iostream.h> does not terminate with a semicolon.

The main() Function


The main() function is mandatory in a C++ program. The program execution always
starts from the main() function.

Example
#include<iostream>
int main()
{
//C++ code
return 0;
}

2.12 Creating Objects


When the main() function completes execution, it needs to notify the operating system
about its completion. This is the reason why the last statement in main() is return 0;.

The operating system considers the number 0 that is returned to it to imply that the
program has completed execution without any errors. If any number other than 0 is
returned to the operating system, it implies that some error has occurred.

The main() function should create the objects of the appropriate classes and invoke
member functions.

Consider the following code snippet:


#include<iostream>
class Car
{
float price;
/* Member functions are declared and defined after the public access
specifier*/
public:
void acceptprice()
{
cout << “Enter Price :”;
cin >> price;
}

void honk()
{
cout <<endl <<"BEEP BEEP!";
}
};
int main()
{
Car ford; //An object named ford of the type Car is created
ford.acceptprice(); //Invokes the member function acceptprice
ford.honk(); //Invokes the member function honk()
return 0;
}

In the above example, the code for object creation and invoking member functions is
written inside the main() function. You will learn more about access specifiers in
subsequent chapters.

Creating Objects 2.13


Note
The program given above also contains comment entries within the '/*' and '*/'
symbols and after the '//' symbol. Comment entries are notes that a programmer
writes anywhere in the code so that any other programmer reading the code will
understand it better. The compiler ignores comment entries, and consequently, they
never appear in the executable code. If a comment entry spans more than one line, it
has to be enclosed within '/*' and '*/' symbols. The '//' symbol treats the rest of the
code line as a comment.

Displaying Formatted Output

You must ensure that the any output generated or displayed by your program is easily
readable and comprehendible by the users. This requires you to format the output that is
generated. C++ provides you with certain manipulators that can be used to format the
output to be displayed on the screen. One of the most commonly used manipulators
provided by C++ is the setw() manipulator.

The setw() manipulator is used to set the width of the field that is to be displayed on the
screen. The required width is provided as a parameter to the manipulator. Consider the
following statement:
cout << setw(10) <<”Bryan”;

In the preceding statement, the width of the text “Bryan” is 5. Since the setw()
manipulator is setting the width to 10, therefore, 5 additional characters will be prefixed
to the original 5 characters, and then the output will be displayed on the screen. The
characters that are prefixed to the original characters are whitespace characters.

The output generated by the preceding statement that includes the setw(10) manipulator
will be:
Bryan

In the preceding output, the “ _” characters prefixed before the text, Bryan, represent
whitespaces. Similarly, if you will display the text Ryan instead of Bryan and apply the
same width of 10 to the text, the output will be prefixed with 6 whitespaces in addition to
the 4 characters of “Ryan”.

Note
To use the setw() manipulator, you must include the iomanip.h header file in your
program.

2.14 Creating Objects


Introducing Functions

Functions are the building blocks of C++ programs. When programs become large, a
single list of instructions becomes difficult to understand. For this reason, functions are
adopted. A function groups a number of program statements into a single unit. A function
has a clearly-defined purpose and a clearly-defined interface to other functions in the
program. A group of functions together form a larger entity called a module. Thus, this
approach to programming, where a program is broken down into smaller modules, is
known as modular programming.

Another reason for using functions is to reduce the program size. Any sequence of
instructions that is repeated in a program can be grouped together to form a function. The
function code is stored in only one place in the memory.

The following program illustrates the use of a function:


//This program uses a function to calculate the sum of two numbers
#include<iostream.h>
void add(); //function prototyping
void main()
{
cout<<”Calling function add() ”<<endl;
add(); //A call to the function add()
cout<<”A return from add() function ”<<endl;
} // while calling a function the command is terminated with a ‘;’
//Function definition for add
void add() {
int iNum1,iNum2,iNum3;
cout<<”Input two numbers “<<endl;
cin>>iNum1;
cin>>iNum2;
iNum3=iNum1+iNum2;
cout<<”The sum of the two numbers is “<<iNum3<<endl;
}

In the above program, the add() function is invoked from main(). The control passes to
the add() function, and the body of the function is executed. The control then returns to
main() and the remaining code is executed.

The sample output of the program that adds two numbers is as follows:
Calling function add()
Input two numbers
10
20

The sum of the two numbers is 30


A return from add( ) function

Creating Objects 2.15


In the given program the main() function, which invokes the add() function, is called the
calling function, and the add() function is the called function.

Function Prototyping
Just as any variable is declared in a program before it is used, it is necessary to declare or
prototype a function to inform the compiler that the function will be referenced at a later
point in the program.

In the given program, the statement:

void add(); is a function declaration or a prototype.

Defining a Function
The function definition contains the code for the function. The function definition for
add() in the given program is:

// Function definition for add


void add()
{
int iNum1,iNum2,iNum3;
cout<<”Input two numbers “;
cin>>iNum1;
cin>>iNum2;
iNum3=iNum1+iNum2;
cout<<”The sum of the two numbers is “<<iNum3;
}

A function declaration can be avoided if the function definition appears before the first
call to the function.

The given program for adding two numbers can be modified to avoid function declaration
as:
//This program uses a function to add two numbers
#include<iostream.h>
void add()
{
int iNum1,iNum2,iNum3;
cout<<”Input two numbers “;
cin>>iNum1;
cin>>iNum2;
iNum3=iNum1+iNum2;
cout<<”The sum of the two numbers is “<<iNum3;
}

2.16 Creating Objects


void main()
{
cout<<”Calling function add() “<<endl;
add(); //A call to the function add()
cout<<”A return from add() function”<<endl;
}

Function Arguments
Argument(s) of a function is/are the data that the function receives when invoked from
another function. It is not always necessary for a function to have arguments. The add()
function did not contain any arguments.

Specifying Argument Data Types

If you are creating a function that accepts argument(s), you must specify the data type of
the arguments in the function declaration. For example, if you are creating a function
named add() that accepts two integer arguments, you can declare the function as:
void add(int, int);

You need to ensure that the function definition also includes the same argument types. For
example, the add() function can be defined as:
void add(int arg1, int arg2) //specifying the argument types as int
{
...
}

To invoke the add() function, you will pass two integer values to the function, as shown
in the following statement:
add(10, 15);

Note that the function call does not require you to provide the type specifiers for the
arguments being passed.

The add() function above that adds two numbers can be modified to accept two
arguments as, as shown in the following program:
#include<iostream.h>
void add(int iVar1,int iVar2) //function containing two arguments
{
int iVar3=iVar1+iVar2;
cout<<”The sum of the two numbers is “ <<iVar3<<endl;
}
void main()
{

Creating Objects 2.17


int iNum1,iNum2;
cout<<”Input two numbers “;
cin>>iNum1;
cin>>iNum2;
add(iNum1,iNum2); //passing two values to the function add()
}

Returning Values from Functions


When a function completes its execution, it can return a single value to the calling
program, which can be trapped when the calling function needs the result of the called
function.

The following program illustrates a function that returns a value:


//This program uses a function to add two numbers and returns the sum
to the calling program
#include<iostream.h>
int add(int, int); //This function returns a value of type int
void main()
{
int iSum,iVar1,iVar2;
cout<<”Enter two numbers “<<endl;
cin>>iVar1;
cin>>iVar2;
iSum = add (iVar1,iVar2);
cout<<”The sum of the two numbers is “<<iSum<<endl;
}
int add(int iNum1, int iNum2)
{
return iNum1+iNum2;
}

When a function returns a value, the data type of the value must be specified before the
function name. In the preceding program, the type int is placed before the add()
function. Functions that return no value have the return type specified as void.

The statement:

iSum=add(iVar1,iVar2); causes the variable iSum to be assigned the value


returned by the function add().

The sample output of the preceding program is as follows:


Enter two numbers
23
37
The sum of the two numbers is 60

2.18 Creating Objects


Default Arguments
C++ allows a function to assign a default value to a parameter when no argument
corresponding to that parameter is specified in the call to that function.

A function that assigns default arguments is illustrated in the following code segment:
int add(int iNum1=10, int iNum2=20)
{
return iNum1+iNum2;
}

In the above code segment, if the add() function is invoked without any arguments, then
the default value of 10 and 20 is assigned to iNum1 and iNum2, respectively. If values are
passed to the function, then corresponding values are assigned to iNum1 and iNum2.

Constant Arguments
There may be situations where you do not want the function to modify the arguments that
you pass to it. In such a situation, you can ensure that the argument that is passed to the
function is a constant. To make an argument as constant, you need to use the const
keyword. For example, if you want that the integer arguments accepted by the add()
function should be constants, you can modify the declaration as:
int add(const int iVar1, const int iVar2);

Creating Objects

A class declaration does not reserve memory at the time of declaration. Memory is
allocated when an instance of the class is created. An instance of a class is called an
object. For example, in the following statement:
int iNum1, iNum2, iNum3;

iNum1, iNum2 and iNum3 are three variables of type int.

NIIT Creating Objects 2.19


Similarly, you can define many objects of the same class as shown in the following figure.

Class

member variable1
member variable2

member function1
member function2

Object 1 Object 2

member variable1 member variable1


member variable2 member variable2

Class and Objects of the Class

All the objects share the same copy of the member functions, but maintain a separate copy
of the member variables.

In the previous chapter, you learned to declare a class named Car. Now, to create an
object named ford of the type Car, you will use the following code:
Car ford;

The member functions of the class are accessed through an object of the class using the ‘.’
operator.

2.20 Creating Objects


Consider the following example:
ford.honk();

In the above example, the object name and the ‘.’ operator is used to access the member
function honk().

Compiling, Linking, and Executing the Program

The compiler, as discussed earlier, is software that translates a program written in a


language like C++ into object code. The object code of the program is the file containing
the translated program. The suffix given to C++ source files will depend on the compiler
in use. Unix-based compilers commonly use a suffix of .cc or .C, or .cxx.
DOS/Windows-based compilers typically use the suffix .cc, .cxx, or .cpp.

After compiling, the object code is linked with libraries. Libraries are a collection of
executable pieces of code that you can reuse in your program. A C++ library contains
object code snippets (called functions) for tasks like drawing a line on the screen and
displaying a character. These tasks are generally done by most programs; hence, they
have been put together in common library files, which every programmer can use.
Various software corporations have added libraries and are selling their implementations
of the C++ language. Hence, we have DJGPP, Borland C++, Symantec C++, Metrowerks
CodeWarrior, IBM VisualAge and KAI C++. These implementations provide Integrated
Development Environments (IDEs). An IDE is software that allows you to write a
program, check it for errors, and translate it into machine language. These tasks are
performed by using a built-in editor, debugger, and compiler, respectively. An IDE also
allows you to link and execute (run) the compiled program.

In this course, you will use Code Blocks for developing applications. You need to
perform the following steps to compile and execute a C++ program by using the Code
Blocks compiler:
1. Press the Windows logo key. The Start screen is displayed.

Creating Objects 2.21


2. Type Code Blocks. The Search pane is displayed, as shown in the following figure.

3. Click the Code Blocks icon on the Start screen. The Start here - Code::Blocks
17.12 window appears, as shown in the following figure.

The Start here - Code::Blocks 17.12 Window

2.22 Creating Objects


4. Creating a New Project in Code Blocks
 Select FileNewProject. The New from template dialog box is displayed,
as shown in the following figure.

The New from template Dialog Box


 Ensure that the Projects option is selected in the left pane of the New from
template dialog box.
 Select the Console application category.

Creating Objects 2.23


 Click the Go button. The Console application wizard appears, as shown in the
following figure

The Console application Wizard

2.24 Creating Objects


 Click the Next button. The Language Selection page appears, as shown in the
following figure.

The Language Selection Page


 Ensure that the C++ language is selected in the Please make a selection list
box.

Creating Objects 2.25


 Click the Next button. The Folder Selection page appears, as shown in the
following figure.

The Folder Selection Page


 Type DemoProject in the Project title text box.
 Click the button adjacent to the Folder to create project in text box to browse
the location where you need to create the project.
 Click the OK button.

2.26 Creating Objects


 Click the Next button. The Compiler Selection page appears, as shown in the
following figure.

The Compiler Selection Page

Creating Objects 2.27


 Click the Finish button. The [DemoProject] - Code::Blocks 17.12 window is
displayed, as shown in the following figure.

The [DemoProject] - Code::Blocks 17.12 Window


 Expand the Sources node of the DemoProject project in the left pane under the
Projects tab of the Management window.

2.28 Creating Objects


Note
In the Code Blocks IDE, “iostream” and “using namespace std” are by
default included. So you can run all your programs without
including any other header file..

Identifying Errors
Before starting the compilation process, you must ensure that the program is error-free.
An erroneous program will not compile. Some of the common types of errors are
categorized as:
 Syntax errors
 Semantics errors
 Logical errors
 Type errors
 Run-time errors

Syntax Errors

Syntax refers to the rules that govern the structuring of statements in a language. You
need to ensure that the statements that you write in your program are syntactically correct.
Consider the following snippet:
void main()
{
cout << “ Hello World”.
}

The preceding snippet when executed in the compiler will result in an error. This is
because, each statement in C++ must terminate with a semicolon (;), which has not been
done in the preceding code snippet. If in a program, you terminate a statement with a
symbol other than the semicolon (;), the program will cause a syntax error.

Semantic Errors

Semantic errors are those that are caused because of statements that are not meaningful.
Semantic refers to the meaning of a statement. The statement that you write may be
syntactically correct, but if the meaning of the statement is not correct, a semantic error
will be raised by the compiler. For example, you always place the expression to be
evaluated on the right-hand side of the assignment operator and the variable to which the
result is assigned is placed on the left-hand side of the assignment operator.

Creating Objects 2.29


However, if you interchange the placement of the expression and the variable, a semantic
error will be raised. This is shown in the following example:
a + b = sum;

The preceding statement will result in a semantic error and the compiler will not execute
the program, even when the syntax of using variables, adding, assigning, and terminating
is correct.

Logical Errors

Logical errors are caused by statements that generate undesirable or unpredicted outputs.
For example, if you have to calculate the average score of 4 subjects but divide the sum of
4 subjects by 3, then this will constitute as a logical error as it will generate an undesirable
result.

Type Errors

Type errors are caused when you pass a type of value that is different than the one that is
expected by the program. For example, if you try to store an integer value in a string
variable, a type error will be raised.

Run-Time Errors

Run-time errors occur while the program is executing. Such errors are a result of certain
illegal operations. For example, during the program, if an expression causes a value to be
divided by zero, a run-time error will occur. Further, if during the execution of a program
there is insufficient memory, a run-time error is raised. Similarly, a run-time error will be
raised if the program tries to open a file that is nonexistent.

2.30 Creating Objects


Introducing Arrays
An array is a collection of elements of a single data type stored in adjacent memory
locations. For example, rather than defining 30 integer variables for storing the scores of
30 students in a class, one integer array can be defined containing 30 elements to store the
data.

The Need for Arrays

To understand the need for an array, let us consider a situation where the information
regarding fifty models of cars needs to be stored. Since a variable is capable of storing
only one value at a time and defining and keeping track of 50 variables in a program is
not easy, the solution is to declare one variable with 50 elements to store the information
about the various car models.

Before an array variable can be initialized, its data type and size (number of elements in
the array) must be defined. The definition and the initialization of an array variable can
occur within the same statement.

Each element of the array can be accessed by its subscript number. The subscript number
specifies the position of an element within the array (also called the index of the element).
The first element of an array has an index 0, and the last element has an index one less
than the dimension size of the array.

All the elements of an array must be of the same data type. Thus, there cannot be an array
with five elements of which three are char elements and two are float elements.

Declaring and Initializing Arrays


This following syntax can be used to declare an array variable:
<data_type> <variable_name>[<dimension_size>];

Example

Consider the following array declaration:


int arr[5];

Creating Objects 2.31


Note
The method for declaring arrays of user-defined data types is the same as the
declaration stated above. For example, if an array is of the user-defined data type Car,
it will be given as: Car car_det[5]

The size of the array is 5. When the array definition is executed, memory is allocated for
the user-defined variable arr. The array elements will be positioned one after the other in
the memory. Following is a schematic representation of the placement of array elements
in the memory.

arr[0] arr[1] arr[2] arr[3] arr[4]

In the above diagram, arr is the name of the array variable. The elements of the array are
arr[0], arr[1], arr[2], arr[3], and arr[4]. Here, 0, 1, 2, 3, and 4 are the
subscripts (or indices) of the elements. Note that the index starts from 0.

In order to initialize this array, you need to initialize the individual elements, as shown in
the following statements:
arr[0] = 14;
arr[1] = 15;
arr[2] = 17;
arr[3] = 45;
arr[4] = 81;

The elements can be initialized in any order. Following is a schematic diagram of the
same array after initialization.

14 15 17 45 81

arr[0] arr [1] arr[2] arr[3] arr[4]

You can also initialize individual elements. For example:


cin >> arr[2]; // The user enters a value to be stored in the
// element with an index of 2

or
arr[4] = arr[0] + arr[2];

2.32 Creating Objects


The array can also be initialized during declaration as shown in the following statement:
int arr[5] = {14, 15, 17, 45, 81};

If you initialize an array at the time of its declaration, then it is not necessary to specify
the dimension of the array, as shown in the following statement:
int arr[] = {14, 15, 17, 45, 81};

Since an array subscript starts from zero, arr[2] refers to the third element in the array.
Therefore, writing cout << arr[2]; will display 17.

Note
You must specify the size of an array at the time of its declaration, unless you are
initializing it in the same statement. Therefore, the following code snippet is incorrect:

char err[]; //ERROR!! will not compile

If you specify the size of an array as 3, and try to initialize more than three elements in
it, the compiler will show a warning and will ignore the last value:

int wrong[3] = {12,56,23,67}; // Warning: excess elements in


// Aggregate initializer

An array cannot be initialized with another array. The only way to copy an array into
another is to copy its individual elements. The following statements show the correct and
incorrect ways to copy elements of an array to another array:
int abc[3] = {100,200,300}, xyz[3]; // Valid declaration
xyz = abc; // ERROR!! an array cannot be initialized with
// another array.
xyz[2] = abc[1]; // Correct
xyz[0] = abc[2]; // Correct
xyz[1] = abc[0]; // Correct

Consider a situation where you need to store details such as the price and mileage of two
popular models of cars.
#include <iostream>
class Car
{
float price;
int mileage;

Creating Objects 2.33


public:
void display()
{
cout << “\n The Price is \t”<<price;
cout << “\n The Average Mileage is \t”<<mileage;
}

void accept()
{
cout<< “\n Enter Price of a model\t”;
cin>>price;
cout<< “\n Enter Company Quoted Mileage\t”;
cin>>mileage;
}
};
int main()
{
Car car_det[2]; // Declares an array of user-defined data
// type populates the array with values
car_det[0].accept();
car_det[1].accept();

// Accesses element-by-element to display values


car_det[0].display();
car_det[1].display();
}

In the above program, an array of two elements is declared by using the statement:
Car car_det[2];

The array is initialized element-by-element by using the following statement:


car_det[0].accept(); //Initialize the values, price and
//mileage of the Car object

One-Dimensional char Arrays


An array of characters stores a string constant and is terminated by a NULL ('\0'). Consider
the following array declaration and initialization:
char str[] = "SANDY";

It can be schematically represented as shown in the following figure.

2.34 Creating Objects


The NULL character ('\0') is automatically inserted at the end of any set of characters
enclosed within double quotes (" "). An array is referred to as a string if it terminates with
a NULL character. The NULL character cannot be displayed on the screen. The array
declaration and initialization of str can also be written as:
char str[6];
str[0] = 'S';
str[1] = 'A';
str[2] = 'N';
str[3] = 'D';
str[4] = 'Y';
str[5] = '\0';

Note
The NULL character has the American Standard Code for Information Interchange
(ASCII) code 0 but is not the same as the digit ‘0’, which has the ASCII code 48.

The following code is a modified version of the program that stores details of cars. This
version of the program displays the model of the car along with the price and mileage:
#include <iostream.h>
#include <stdio.h> // for implementing getchar()
#include <conio.h> // for implementing clrscr()
class Car
{
float price;
int mileage;
char model[30];
public:
void display()
{
cout<< “\n The Model of Car is \t”<<model;
cout << “\nThe Price is \t”<<price;
cout << “\n The Average Mileage is \t”<<mileage;
}

void accept()
{
cout<< “\n Enter the Model of the Car\t”;
cin>>model;
cout<< “\n Enter Price of a model\t”;
cin>>price;
cout<< “\n Enter Company Quoted Mileage\t”;
cin>>mileage;
}
};

Creating Objects 2.35


int main()
{
Car car_det[2]; // Declares an array of user-defined data
// type Populates the array with values
car_det[0].accept();
car_det[1].accept();
// Accesses element-by-element to display values
car_det[0].display();
car_det[1].display();
}

Using String Functions

Even though you can use the cin object to accept input and the cout object to display
output for character arrays, these objects are not exclusively meant for string
manipulations. C++ provides you with string functions for manipulating strings. The
functions, gets() and puts() allow you to accept input for and display the value stored
in string arrays, respectively. You can also use the puts() function to display string
literals on the screen.

Consider the following snippet:


char designation[20];
puts(“Enter Designation”);
gets(designation);
puts(designation);

The preceding statements declare a character array, designation. The puts() function
displays the text “Enter Designation” on the screen. The gets() function allows you to
store the input provided by the user in the character array, designation. Next, the puts()
function displays the value stored in the string array. Each puts() statement displays the
output in a new line.

Note
The cin object does not accept whitespaces, whereas, the gets() function allows you
to enter strings that include white spaces.

2.36 Creating Objects


Activity: Introducing Arrays

Problem Statement
As a member of a team that is developing the billing system software for Diaz
Telecommunications, Inc., you have been assigned the task of creating a software module
that accepts the following customer details and displays it:
 Mobile number, containing a maximum of 12 characters
 Name, containing a maximum of 25 characters
 Date of birth, containing a maximum of 10 characters
 Billing address, containing a maximum of 50 characters
 City, containing a maximum of 25 characters
 Residence phone number, containing a maximum of 13 characters.
 Amount outstanding, containing decimal values

Solution
#include <iostream>
class Customer
{
private:
char mobileNo[13];
char name[26];
char dateOfBirth[11];
char billingAdd[51];
char city[26];
char phoneNo[14];
float amountOutstanding;
public:
void print()
{
cout << endl << "Mobile phone number: ";
cout << mobileNo << endl;
cout << "Name: ";
cout << name << endl;
cout << "Date of Birth: ";
cout << dateOfBirth << endl;
cout << "Billing Address: ";
cout << billingAdd << endl;
cout << "City: ";
cout << city << endl;
cout << "Residence phone number: ";
cout << phoneNo << endl;
cout << "Amount due: ";
cout << amountOutstanding << endl;
}

Creating Objects 2.37


void get()
{
cout << "Mobile phone number: ";
cin >> mobileNo;
cout << endl << "Name: ";
cin >> name;
cout << endl << "Date of Birth: ";
cin >> dateOfBirth;
cout << endl << "Billing Address: ";
cin >> billingAdd;
cout << endl << "City: ";
cin >> city;
cout << endl << "Residence phone number: ";
cin >> phoneNo;
cout << endl << "Amount due: ";
cin >> amountOutstanding;
}
};
int main()
{
Customer object;
object.get();
object.print();
return 0;
}

After saving and compiling the program, execute the program to enter the following
highlighted information:
Mobile phone number: 678-295-9518
Name: Michael
Date of Birth: 10/8/1971
Billing Address: 14, George Street, New York
City: California
Residence phone number: 534-177-3312
Amount due: 0

The following output will be generated:


Mobile phone number: 678-295-9518
Name: Michael
Date of Birth: 10/8/1971
Billing Address: 14, George Street, New York
City: California
Residence phone number: 534-177-3312
Amount due: 0.00

2.38 Creating Objects


Introducing Structures
Arrays allow you to group values of the same type under one name. However, in a
real-life scenario, a record may contain values of various types. For example, an
application that stores details about students will require information such as student
names, roll numbers, marks, or class. Such data is of varied types and cannot be stored in
an array because it allows you to store data of only one type. To accomplish such a task,
C++ includes the concept of structures.

Almost all applications need to store data for future use. Most of the times, this data is a
logical group of related information, such as employee details, product details, or student
details. The storage and retrieval of such data will be easier if it is stored in the form of
records. C++ provides structures that allow you to store information as a record. You can
use structures to group various types of data under one name.

Defining Structures

Structures are defined by using the struct keyword. Consider the following record
definition:
struct salesdata{
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
};

In the preceding definition, salesdata is the identifier of the structure that will store sales
records with details such as transaction number, salesman number, and product number.

Here, the struct keyword declares that the variables are to be treated as one unit called
salesdata. As in the case of other declarations, the struct declaration also ends with a
semi-colon.

The preceding snippet just defines the form of the structure and does not allocate memory
for the structure. To allocate memory to the structure, you need to declare a structure
variable.

Creating Objects 2.39


You can modify the structure definition to declare a structure variable, as shown in the
following code snippet:
struct salesdata{
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
} salesrec;

In the preceding snippet, a structure variable, salesrec, has been declared. The structure
variable can be used to access the member variables of the structure.

You can also declare a structure variable by using the following syntax:
struct struct_name{
...
...
...
...
};
struct_name struct_variable;

The preceding method of declaring a structure variable does not require you to declare the
variable along with the definition. Therefore, you can declare a structure variable
anywhere in your program.

Thus, the structure variable for the salesdata structure can be declared as:
struct salesdata
{
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
};
salesdata salesrec;

The advantage of this method of declaration is evident when the structure salesrec has
to be passed to a function. Instead of declaring the entire structure type in the called
function, the parameter of the function can be declared to be of the structure type
salesdata in the same way that salesrec has been declared.

After you have created a structure variable, you can access the member variables of the
structure by using the dot operator. For example salesrec.salesno refers to the
variable salesno. Similarly, salesrec.transno[1] refers to the second element of the
array transno.

2.40 Creating Objects


Array of Structures

As in the case of other data types, it is possible to define an array of structures. You can
create an array of a structure to store multiple records. Consider that you have a structure
that includes three variables for storing student name, roll number, and score. A single
structure variable will allow you to store only one student record. However, if you create
an array of the structure, you can store multiple records of students, depending on the size
of the array.

Consider the following structure declaration:


struct stud_details
{
char Student_Name[30];
int Roll_No;
float Score;
};

If there are 20 students in a class, an array of the structure to hold 20 records has to be
created in the system memory. The array members can be initialized while declaring the
array of a structure.

Consider the following statement that declares an array of a structure:


Student_details stud_records[] ={
{"Sach",1,0},
{"Jim",2,0,},
{"Bryan",3,0,},
{"Steven",4,0}
};

Note that each set of values for the array has been enclosed in braces ({…}). This is not
essential but improves clarity of the code. You can refer to any member of the structure
by using an index along with the name of the array.

Therefore, stud_records[l].Student_Name refers to the value, Jim, stored in the


Student_Name variable of the second record while, stud_records[1].Student_Name [0]
refers to the character ’J’ in the name ”Jim”.

The following code snippet depicts how to create and use an array of a structure:
#include<iostream.h>
#include<conio.h>
#include <stdio.h>
struct Student_details
{
char Student_Name[30];
int Roll_No;
int score;

Creating Objects 2.41


};

void main()
{
clrscr();
Student_details stud_records[] = {
{"Sach",1,0},
{"Jim",2,0,},
{"Bryan",3,0,},
{"Steven",4,0}
};

cout<<stud_records[0].Student_Name<<endl;
cout<<stud_records[0].Roll_No<<endl;
cout<<stud_records[1].Student_Name<<endl;
cout<<stud_records[1].Roll_No<<endl;
getch();
}

2.42 Creating Objects


Practice Questions
1. As a part of the team that is developing the billing system software for Diaz
Telecommunications, Inc., you have been assigned the task of writing a program that
accepts dealer details. The details to be captured are given below:
a. First Name
b. Last Name
c. City
d. Phone number
Write a C++ program to accept and display the dealer details. The dealer details
should be displayed in the following format:
First name: Last name:
City: Phone number:

2. Predict the output of the following code:

#include <iostream.h>
void main()
{
char ch=’A’;
char ch1=66;
int i=60.00;
cout<<ch<<endl<<ch1<<endl<<i;
}

3. Predict the output of the following code:

#include <iostream.h>
class Customer
{
public:
int age;
};
void main()
{
Customer obj1, obj2;
cout<<”Enter the first customer’s age:”;
cin>>obj1.age;
obj2=obj1;
cout<<obj1.age<<” is the age of customer1”<<endl;
cout<<obj2.age<<” is the age of customer2”<<endl;
}

Creating Objects 2.43


Summary
In this chapter, you learned that:
 A variable is a named location in memory that contains a specific value.
 A data type defines the type of data that can be stored in a variable.
 The cin object is used to accept input from the keyboard.
 The cout object is used to display output to the screen.
 The contents of header files are inserted into a program with the #include directive.
 The C++ program execution starts from the first statement of the main() function.
 The smallest element of a program understandable by the C++ compiler is known as
a token.
 Literals are data items whose values do not change during the execution of a
program.
 The setw() manipulator is used to set the width of the field that is to be displayed on
the screen.
 Comment entries are notes that a programmer writes anywhere in the code so that
any programmer reading the code will understand it better.
 An object is an instance of a class.
 The compiler is a software that translates a program written in a language like C++
into machine language and the file containing the translated program is called the
object code of your program.
 Linking combines your object code with the object code of the functions you use and
adds some standard startup code to produce a run-time version of your program.
 Some of the common types of errors are categorized as:
 Syntax errors
 Semantics errors
 Logical errors
 Type errors
 Run-time errors
 An array is a collection of elements of a single data type stored in adjacent memory
locations.
 The array can be initialized when it is defined or later.
 An array must be given a constant dimension size, which should be at least 1.
 Each element of an array can be accessed by its subscript number.
 C++ provides you with structures that allow you to store information as a record.
 You can create an array of a structure to store multiple records.

2.44 Creating Objects


Exercises

Exercise 1
You have defined an Employee class as part of developing a software application for Diaz
Telecommunications, Inc. The class, which you have defined, is as follows:
class Employee
{
char firstName;
char lastName;
char dateOfBirth;
char dateOfJoining;
char city;
char phoneNo;
public:
void accept()
{
//Code to accept employee details
}
void display()
{
//Code to display employee details
}
}

The Employee class definition shown above contains errors and is incomplete. Identify
and fix the errors. Complete the code in the Employee class definition and write the
main() function. Compile and execute the code.

Exercise 2
Jim works for an airline company. Customers fill the Booking Request Form with the
details of the flight like the flight number, destination, and date and hand it over to Jim.
He then books tickets for the customers based on the availability of seats.

Identify the classes and objects involved in the above scenario and their attributes. Write
methods in the class to accept and display the values of the different attributes.

Creating Objects 2.45


Exercise 3
The following program should interchange the values of two variables var1 and var2 and
should print the new values of the variables. However, the program does not generate the
desired output. Identify the error in the program and write the correct code.
#include<iostream>
class interchange
{
private:
int var1;
int var2;
int temp;
void swap()
{
var1=5;
var2=10;
temp=var1;
var1=var2;
var2=var1;
}
void display()
{
cout<<"The new value of variable1 is:"<<var1<<endl;
cout<<"The new value of variable2 is:"<<var2<<endl;
}
};
void main()
{
interchange I1;
I1.swap();
I1.display();
}

Exercise 4
You need to write a program that accepts and displays the details of a specified number of
candidates who want to register in the gym, SuperGym. The details should include:
 candidate_id, containing integer type of data.
 candidate_name, containing a character array of length 30 characters.
 candidate_age, containing float type of data.

2.46 Creating Objects


Exercise 5
Consider a structure, studentresult that contains the rollno and the marks in
Physics, Chemistry, and Maths of 50 students. The maximum marks in each subject are
100. The studentresult structure is defined as:
struct studentresult
{
float Phy_Marks, Chem_Marks, Maths_Marks;
} studentarray[50];

Now, you need to write a program that uses a function student to calculate:
 The number of students passed with distinction.
 Number of students failed.

For distinction, a student needs to score at least 70% and minimum passing marks is 35%.

Creating Objects 2.47


CH AP T E R 3

In object-oriented programming, data and the methods that can operate on the data are
clubbed as a single unit. This concept is known as encapsulation. Similarly, in object-
oriented programming, only the relevant data is exposed, hiding the rest of the data. This
concept is known as abstraction.

This chapter introduces the concept of encapsulation and abstraction. It discusses the
implementation of encapsulation by using access specifiers. In addition, it explains the
concept of static variables, functions, and friend functions.

Objectives

In this chapter, you will learn to:


 Understand access specifiers
 Use static variables and functions
 Use friend functions and classes

3.2 Encapsulation and Abstraction


Access Specifiers
Over the years, European automobile salesmen have evolved a foolproof (so they claim)
method of identifying the nationality of a prospective buyer without ascertaining his/her
name. In fact, they have become so adept at it that they claim a 95 percent success rate at
this game. Some of the results of their observations are: “A German is interested in the
speed of the car, an American in its price, the Italian always tests its horn, the Englishman
is interested in its engine, and the Frenchman on the style and lines.”

The above story, however doubtful of its authenticity, underlines an important reality – in
a complex world, neither does every individual concentrate nor does one need to
concentrate on every aspect of a given entity.

Similarly, a housewife would typically pay attention to the size, ease of handling, and
durability of a vacuum cleaner (she would not be interested in the gadgetry inside it, that
is in the purview of the maintenance man); sales personnel may concentrate on entirely
different factors. There is a term given to the above process: abstraction.

The Object Oriented approach also works on the same concept. It hides the unnecessary
details of a program and shows only the essential characteristics of the program to the
user. This process is known as abstraction.

Abstraction and Encapsulation

“Abstraction denotes the essential characteristics of an object that distinguishes it from


all other kinds of objects and thus provides crisply defined conceptual boundaries,
relative to the perspective of the viewer.”

- Grady Booch

Unable to deal with the complexity of an object, humans choose to ignore its non-essential
details and concentrate on the details that are essential to our understanding. Put very
simply and in context of the object model, abstraction means ‘looking for what you want’
in an object or a class.

There is another important concept connected to abstraction. It is called encapsulation.

“Encapsulation is the process of hiding all of the details of an object that do not
contribute to its essential characteristics.”

- Grady Booch

Encapsulation and Abstraction 3.3


Encapsulation literally means ‘to enclose in, as if in a capsule’. Encapsulation is defined
as the process of enclosing one or more items within a physical or logical package. It
involves preventing access to nonessential details.

Therefore, when a housewife plugs in the cord of the vacuum cleaner and clicks on the
switch, the vacuum cleaner starts smoothly. She cannot, and does not, get to see the
complex processes needed to actually convert the electricity into suction power. In other
words, the exact working of the cleaner has been encapsulated. Encapsulation is also
called information hiding or data hiding, since it involves hiding many of the important
details of an object from the user.

Abstraction and encapsulation are different but related features. Abstraction enables you to
make the relevant information visible. Encapsulation enables you to package information
to implement the desired level of abstraction. Therefore, encapsulation assists abstraction
by providing a means of suppressing the nonessential details.

Implementing Abstraction and Encapsulation using Access


Specifiers

An access specifier is used to determine whether any other class or function can access
the member variables and functions of a particular class. C++ supports the following three
access specifiers:
 public
 private
 protected

Access specifiers define the boundary between the accessible and inaccessible parts of a
class. It is the privilege of the designer of the class to demarcate which parts of a class
need to be obscured from the users view and which should be offered to them as an
interface to the class. Thus, you can use the access specifiers to implement encapsulation
and abstraction in C++.

The public Access Specifier


The public access specifier allows a class to expose its member variables and member
functions to other functions and objects.

Consider the following code snippet:


#include<iostream>
class Car
{
public:
char color[21]; //Since the color variable is public, it can

3.4 Encapsulation and Abstraction


//be accessed outside the class definition.
};
int main()
{
Car ford;
cin >> ford.color; /* The . operator is used to access
member data and functions */
return 0;
}

In the above example, the variable color can be accessed from any function. Consider the
following code snippet that includes a public function:
#include<iostream>
class Car
{
public:
char color[15];
void honk()
{
cout << "PARRP PARRP!" << endl;
}
};

int main()
{
Car ford;
ford.honk(); //Displays PARRP PARRP!
return 0;
}

In the above example, the honk()function will be accessible from anywhere in the
program to any function.

The private Access Specifier


The private access specifier allows a class to hide its member variables and member
functions from other class objects and functions. This feature of insulating data from
direct access by other parts of the program is called data hiding. Data hiding protects data
from external alteration, except by the use of public functions. An object's function
provides the only way to access the data. Thus the data is hidden and is safe from
accidental alteration. Data hiding and abstraction are the key terms used for describing an
object-oriented language.

Consider the following code snippet:


#include<iostream>
class Car
{
private:
char model[21];

Encapsulation and Abstraction 3.5


void honk()
{
cout << "PARRP PARRP!" << endl;
}
public:
void setModel()
{
cout << "Enter the model name: ";
cin >> model;
}
void displayModel()
{
cout << "The model is: " << model << endl;
}
};
int main()
{
Car ford;
ford.setModel(); //Accepts the model name
ford.displayModel(); //Displays the model name

ford.honk(); //error! private members cannot be


//accessed outside the class definition
cin >> ford.model; //error! private members cannot be
//accessed outside the class definition
return 0;
}

In the above example, the setModel() and displayModel() functions can be called from
the ford object defined in the main() function. However, the model variable cannot be
accessed through the ford object since it is a private member variable. Similarly, the
honk() function cannot be accessed through the ford object, since it is a private member
function.

The default access specifier for a class member is private. In the following example, the
model member variable is private even though it has not been specified explicitly:

class Car
{
char model[21];
public:
...
};

The protected Access Specifier


Like the private access specifier, the protected access specifier also allows a class to
hide its member variables and member functions from other class objects and functions.
The significant use of the protected access specifier is while implementing inheritance,
which will be discussed in the chapter on inheritance.

3.6 Encapsulation and Abstraction


Consider the following code snippet:
#include<iostream>
class Car
{
private:
float price;
protected:
char model[21];
void honk()
{
cout << "PARRP PARRP!" << endl;
}
public:
void setModel()
{
cout << "Enter the model name: ";
cin >> model;
}
void displayModel()
{
cout << "The model is: " << model << endl;
}
};
int main()
{
Car ford;
ford.setModel(); //Accepts the model name
ford.displayModel(); //Displays the model name

ford.honk(); //ERROR! Protected members cannot be


//accessed outside the class definition
cin >> ford.model; //ERROR! Proected members cannot be
//accessed outside the class definition
return 0;
}

In the above example, the setModel() and displayModel() functions can be called from
the ford object defined in the main() function. However, the model variable cannot be
accessed through the ford object since it is a protected member variable. Similarly, the
honk() function cannot be accessed through the ford object since it is a protected
member function.

Encapsulation and Abstraction 3.7


The following table shows the visibility of class members for all the three access
specifiers.

Access Visible to own class members Visible to objects of same/other class


specifier

Public Yes Yes

Private Yes No

protected Yes No

Visibility of Class Members

3.8 Encapsulation and Abstraction


Static Variables and Functions

Static Variables

You already know that each object has its own set of member variables. However, in
some situations, it is preferable to have one or more variables that are common for all
objects. C++ provides static variables for this purpose.

As its name suggests, static variables retain their value even after the function to which
it belongs has been executed. This means that a static variable retains its value throughout
the program.

Note
The static variables have to be initialized explicitly either inside the class declaration
or outside the class.

Static variables are initialized outside the member function or class definition. The
following example illustrates the declaration and initialization of a static variable:
class staticExample
{
int data;
static int staticVar; // Static variable declared
public:
//Definition of member function
};
int staticExample :: staticVar=0; //Static variable initialized to 0

In the above example, a static variable is initialized outside the class definition. Creating
more than one object will not reinitialize the static variable. Unlike member variables, only
one copy of static variable exists in the memory for all objects of that class. Thus, all
objects share one copy of the static variable in memory. Consider a situation where you are
required to keep track of the number of objects created for a given class. If you declare a
non-static member variable called counter, every instance of that class will create a
separate variable, and there will be no single variable having a count of the total number
of objects created. To avoid this, you can use static member variables because it is this
single static variable that gets incremented by all objects.

Encapsulation and Abstraction 3.9


Note
The :: operator is known as the scope resolution operator. It is used to access the
members of a class from outside the class.

You can also initialize the static variable inside the class definition, as shown in the
following example:
#include <iostream>
class myclass
{
void increment()
{
static int i=5;
cout<<i<<endl;
i++;
}
public:
void display()
{
cout<<"calling increment for first time"<<endl;
increment();
cout<<"calling increment for second time"<<endl;
increment();
}
};
int main()
{
myclass m1;
m1.display();
return 0;
}

Static Functions

Like static variables, you can also declare a function to be static. Static functions can only
access static variables and not non-static variables. You use the class name to access the
static functions, as shown below:
ClassName::StaticFunctionName ;

3.10 Encapsulation and Abstraction


The following code snippet shows the use of static functions:
class staticExample
{
int data;
static int staticVar; // Static variable declared
public:
static void display()
{
cout<<"staticVar= "<< staticVar;
cout<<"data= "<<data; //Error! Static functions
//cannot access non-/static variables.
}
};

int staticExample :: staticVar=0; //Static variable initialized to 0


void main()
{
staticExample::display(); //Without creating an object of a class,
//the static function can be accessed
}

In a situation where you want to check whether any object of a class has been created, you
make use of static functions because they come into existence even before the object is
created.

Encapsulation and Abstraction 3.11


Friend Functions and Classes

Friend Functions

If a member of a particular class is private or protected, functions outside the class


cannot access the non-public members of the class. This is the primary objective of
encapsulation. However, at times, it becomes a problem for the programmer. In order to
access the non-public members of a class, C++ provides the friend keyword.

Any non-member function may be declared a friend by a class, in which case the
function may directly access the private member attributes and methods of the class
objects. Consider the following code snippet:
class Z
{
friend void fn();
private:
int a;
};
void fn()
{
Z one;
one.a=5; // Okay, as fn() is a friend
}
void fn1()
{
Z one;
one.a=5; // Wrong as fn1 is not a friend of 'Z'
}

Note that 'fn()' is a global (non-member) function that has been declared a friend.
Member functions of other classes may also be declared as friends by declaring the class
as a friend class.

friend functions are used when the design of a class requires that another class or
non-member function should access the private elements of the class. In such a case,
friend function declarations may be used to enable the class to access those variables
directly.

3.12 Encapsulation and Abstraction


Friend Classes

Just as a function can be made a friend of a class, a class can also be made a friend of
another class:
class distance
{
...
friend class length;
...
};

In this example, the length class is the friend of the distance class. All the members
of the distance class can now be accessed from the length class. The program below
illustrates an entire class declared as a friend of another class:
#include<iostream>
class class1
{
private:
int i;
public:
friend class class2;
};
class class2
{
public:
void func()
{
class1 A1;
cout<<"The value of i in class class1 is "<<A1.i<<endl;
//The function can access the private data of class1
}
};
int main()
{
class2 B1;
B1.func();
return 0;
}

In the preceding program, the class2 class is a friend of the class1 class. Now, all the
member functions of class2 class can access the non-public data of class1.

Encapsulation and Abstraction 3.13


Practice Questions
1. How does a class accomplish data abstraction and encapsulation?

2. What is the difference between a friend function and a friend class?

3. Define a class worker with the following specification:


 Private members:
 wrkname, containing 25 characters.
 hrwrked and wagerate, containing float type data.
 totalwage, containing float type data (hrwrked * wagerate).
 calcwage ( ), a function to find totalwage with float as return type data.
 Public members:
 input_data(), a function to accept values of all private members and to
invoke calcwage.
 output_data(), a function to display all the private members.

4. Predict the output of the following program:

#include <iostream.h>
class Counter
{
private :
unsigned int count;
public:
Counter ( ) {count = 0;}
void inc_Count ( ) { count ++;}
int get_Count( ) {return count;}
};
void main( )
{
Counter C1, C2;
cout<<”\n C1=”<<C1.get_Count( );
cout<<”\n C2=”<<C2.get_Count( );

C1.inc_Count( );
C2.inc_Count( );
C2.inc_Count( );
cout<<”\n C1=”<<C1.get_Count( );
cout<<”\n C2=”<<C2.get_Count( );
}

3.14 Encapsulation and Abstraction


Summary
In this chapter, you learned that:
 Abstraction denotes the essential characteristics of an object that distinguishes it from
all other kinds of objects and thus provides crisply defined conceptual boundaries,
relative to the perspective of the viewer.
 Encapsulation is the process of hiding all of the details of an object that do not
contribute to its essential characteristics.
 An access specifier is used to determine whether any other class or function can
access the member variables and functions of a particular class.
 C++ supports three access specifiers:
 public
 private
 protected
 The public access specifier allows a class to subject its member variables and
member functions to other functions and objects.
 The private access specifier allows a class to hide its member variables and member
functions from other class objects and functions.
 The protected access specifier allows a class to hide its member variables and
member functions from other class objects and functions just like private access
specifier is used while implementing inheritance.
 The static variable retains its value even after the function to which it belongs has
been executed.
 Static functions can only access static variables; non-static variables cannot be
accessed using static functions.
 Any non-member function may be declared a friend by a class, in which case the
function may directly access the private member attributes and methods of the class
objects.
 A class can also be made a friend of another class.

Encapsulation and Abstraction 3.15


Exercises

Exercise 1
You have defined a Dealer class as part of developing the billing system software for
Diaz Telecommunications, Inc. The class, which you have defined, is as follows:
class Dealer
{
private:
char mobileNo[11];
char dealerName[25];
char dealerAddress[51];
char dealerCity[25];
char phoneNo[11];

public:
static int CompanyID
static void showID()
{
cout<<"The dealer name is"<<dealerName;
cout<<"The company ID is"<<CompanyID;
}
void get()
{
//Code to accept the dealer details
}
void print()
{
//Code to print the dealer details
}
};
int CompanyID=6519;

The Dealer class definition shown above is incorrect. Identify the errors in the Dealer
class and write a correct definition for it.

3.16 Encapsulation and Abstraction


erators and Decision-Making Constructs

CH AP T E R 4

While programming, you may come across various situations where you need to perform
computations on data. Similarly, you may come across situations that involve
decision-making and iterative tasks. Such situations can be handled by using the various
types of operators, decision-making constructs, and looping constructs provided in C++.

This chapter discusses the various types of operators, provided in C++, with their
precedence. It also discusses the various conditional and looping constructs provided in
C++. In addition, it discusses the scope of variables.

Objectives

In this chapter, you will learn to:


 Use operators
 Identify operator precedence
 Use conditional constructs
 Use loop constructs
 Identify scope of variables

Operators and Decision-Making Constructs 4.1


Operators
Operators are used to compute and compare values and test conditions. They can be
classified as:
 Arithmetic operators
 Assignment operators
 Unary operators
 Comparison operators
 Logical operators
 Conditional operators

Arithmetic Operators

You use arithmetic operators to perform arithmetic operations, such as addition,


subtraction, multiplication, and division. In the following arithmetic expression:
 x = y + z, y and z are the operands for the '+' operator, and x and y are the operands
for the '=' operator.

The following table shows the arithmetic operators.

Operator Description Example Explanation

Adds the operands x = y + z Adds the value of y and z and


+
stores the result in x

Subtracts the right operand x = y - z Subtracts z from y and stores the


-
from the left operand result in x

Multiplies the operands x = y * z Multiples the values y and z and


*
stores the result in x

Divides the left operand by x = y / z Divides y by z and stores the result


/
the right operand in x

Calculates the remainder of x = y % z Divides y by z and stores the


%
an integer division remainder in x

Arithmetic Operators

Operators and Decision-Making Constructs 4.3


If an expression involves more than one operator, C++ uses the precedence rules to decide
which operator should be used first. If two operators have the same precedence, C++ uses
the associativity rules for evaluating an expression.

Example
int x = 7 + 3 * 6;
cout << x << endl; // Output would be 25
int y = 100 / 4 * 5;
cout << y << endl; // Output would be 125

To understand the above outputs, consider the following precedence and associativity
table for arithmetic operators.

Type Operators Associativity

Value construction () Innermost to outermost

Multiplicative * / % Left to right

Additive + - Left to right

Rules for Precedence and Associativity

Thus, '*' has a higher precedence than '+', and '/' has the same precedence as '*'. In the
expression, int x = 7 + 3 * 6;, the part 3 * 6 is evaluated first and the result 18 is
added to 7. And in the expression int y = 100 / 4 * 5;, the part 100/4 is evaluated first,
since the operator '/' is to the left of the operator '*'.

You can change the precedence and associativity of the arithmetic operators by using the
operator '()' since the '()' operator has the highest precedence among the three types
being discussed. The '()' operator has left to right associativity for evaluating the data
within it.

Example
int x = (7 + 3) * 6;
cout << x << endl; // Output is 60
int y = 100 / (4 * 5);
cout << y << endl; // Output is 5
int z = 7 + ( 5 * (8 / 2) + (4 + 6));
cout << z << endl; // Output is 37

4.4 Operators and Decision-Making Constructs


The modulus operator '%' returns the remainder of an integer division. The following
statements explain the working of the modulus operator:
cout << 7 % 3 << endl; // Output is 1
cout << 0 % 3 << endl; // Output is 0
cout << 1 % 3 << endl; // Output is 1

Note
The modulus operator works only with int operands.

Arithmetic Assignment Operators

You use the assignment operator '=' to assign the value of the right operand to the left. For
example, the statement x=y assigns the value of y to x. You can also assign values to more
than one variable at the same time. Here, the values will be assigned from the right to the
left.

Example
x = y = 0;
In the example given above, y will be initialized before x.

C++ also offers a condensed approach to perform calculations by using arithmetic


assignment operators, which combines an arithmetic operator (+,-,*,/,%) and the
assignment operator (=).

The statement count=count+2 increments the value of the variable count by 2. This
statement can be modified by using the arithmetic assignment operator (+=), as shown in
the following example:
count+=2; //Is the same as count=count+2
count-=2; //Is the same as count=count-2

Operators and Decision-Making Constructs 4.5


The following table shows the different arithmetic assignment operators.

Operator Description Example Explanation

+= Adds the operands and assigns x += y Adds the value of y to x and stores
the result to the left operand the result in x
The expression can also be written as
x = x + y

-= Subtracts the right operand from x -= y Subtracts y from x and stores the
the left operand and stores the result in x
result in the left operand
Equivalent to x = x - y

*= Multiplies the left operand by the x *= y Multiplies the values of x and y and
right operand and stores the stores the result in x
result in the left operand
Equivalent to x = x * y

/= Divides the left operand by the x /= y Divides x by y and stores the result in
right operand and stores the x
result in the left operand
Equivalent to x = x / y

%= Divides the left operand by the x %= y Divides x by y and stores the


right operand and stores the remainder in x.
remainder in the left operand
Equivalent to x = x % y

Arithmetic Assignment Operators

4.6 Operators and Decision-Making Constructs


Unary Operators

The unary operators operate on one operand. The following table explains the two unary
operators, increment and decrement.

Operator Description Example Explanation

++ An increment operator x++ Equivalent to x = x + 1


increases the value of the
operand by one

-- The decrement operator x-- Equivalent to x = x - 1


decreases the value of the
operand by one

Unary Operators

Prefix and Postfix Notations


The increment and the decrement operator ++ and -- can be used in two ways. Let us look
at the increment operator in detail. The two ways in which the increment operator can be
used are:
 As a prefix, where the operator precedes the variable, such as in ++ivar;
 As a postfix, where the operator follows the variable, such as in ivar++;

The following code snippet differentiates the two notations:


var1 = 10;
var2 = ++var1;

The equivalent of this code is:


var1 = 10;
var1 = var1 + 1; // Could also have been written as var1 += 1;
var2 = var1;

In this case, both var1 and var2 are set to 11.

However, if the code is written as:


var1 = 10;
var2 = var1++;

Operators and Decision-Making Constructs 4.7


the equivalent code will be:
var1 = 10;
var2 = var1;
var1 = var1 + 1; // Could also have been written as var1 += 1;

Here, var1 is set to 11, but the value of var2 is 10.

The decrement operator can also be used in both the prefix and postfix forms.

If the operator is to the left of the expression, the value of the expression is modified
before the assignment. Conversely, when the operator is to the right of the expression,
increment or decrement occurs only after the assignment. Therefore, in the statement
var2 = var1++; the original value of var1 is assigned to var2. In the statement
var2 = ++var1;, the incremented value of var1 is assigned to var2.

Comparison Operators

Comparison operators, which are also called relational operators, are used to compare
two values. Comparison operators evaluate to true or false.

The following table shows various comparison operators.

Operator Description Example Explanation

== Evaluates whether or not the x == y Returns true if the values are equal
operands are equal. and false otherwise

!= Evaluates whether or not the x != y Returns true if the values are not
operands are not equal equal and false otherwise

> Evaluates whether or not the x > y Returns true if x is greater than y and
left operand is greater than false otherwise
the right operand

< Evaluates whether or not the x < y Returns true if x is less than y and
left operand is less than the false otherwise
right operand

>= Evaluates whether or not the x >= y Returns true if x is greater than or
left operand is greater than or equal to y and false otherwise
equal to the right operand

4.8 Operators and Decision-Making Constructs


Operator Description Example Explanation

<= Evaluates whether or not the x <= y Returns true if x is less than or equal
left operand is less than or to y and false otherwise
equal to the right operand

Comparison Operators

Logical Operators

Logical operators are used to combine two or more expressions. C++ provides the
AND(&&), the OR(||), and the NOT(!) logical operators. The following table shows
various logical operators.

Operator Description Example Explanation

&& Evaluates to true, if x > 5 && y < 10 The result is true if


both the conditions condition1 (x>5) and
evaluate to true, condition2 (y<10) are
false otherwise both true. If one of
them is false, the
result is false.

|| Evaluates to true, if at x > 5 || y < 10 The result is true if


least one of the either condition1 (x>5)
conditions evaluates to or condition2 (y<10) or
true, and false if both evaluate to true.
none of the conditions If both the conditions
evaluate to true. are false, the result is
false.

! The effect of the ! !(x==0) The result is true, if the


operator is that the condition (x==0) is
logical value of its false. If the same
operand is reversed. condition is true then
the result is false.

Logical Operators

The operators, && and ||, are called short circuit operators. Short circuit operators do
not evaluate the second expression if the result can be obtained by evaluating the first
expression alone.

Operators and Decision-Making Constructs 4.9


Consider the following example:
x < 5 && y > 10;

The second condition (y > 10) is skipped if the first condition is false, since the entire
expression will anyway be false. Similarly with the || operator, if the first condition
evaluates to true, the second condition is skipped as the result will anyway be true.

4.10 Operators and Decision-Making Constructs NIIT


Operator Precedence
The order in which the operators are applied to values is known as the operator
precedence. All the operators within a group have the same precedence and associativity.
The following table lists the precedence order of some of the commonly used operators in
C++.

Precedence Operator Meaning

1 ++ Increment operator, postfix

-- Decrement operator, postfix

2 (all unary) + Unary plus (positive sign)

- Unary minus (negative sign)

++ Increment operator, prefix

-- Decrement operator, prefix

* Multiply

/ Divide

3 (all binary) % Modulus (remainder)

+ Addition

- Subtraction

4 (all binary) < Less than

<= Less than or equal to

5 >= Greater than or equal to

> Greater than

== Equal to

!= Not equal to

Operators and Decision-Making Constructs 4.11


Precedence Operator Meaning

6 = Simple assignment

7 *= Multiply and assign

8 /= Divide and assign

%= Take remainder and assign

+= Add and assign

-= Subtract and assign

Operator Precedence

Expressions in C++

An expression in C++ is a combination of operators and operands and is used to compute


values from the operands. C++ allows you to use various types of expressions, such as
arithmetic or logical (relational). An expression that contains only arithmetic operators is
called an arithmetic expression, whereas, an expression that contains only logical or
relational operators is known as a logical or relational expression.

Arithmetic Expressions
Arithmetic expressions include two types of expressions, integer expressions and real
expressions. The type of arithmetic expression that is created depends on the type of
operators and operands that you combine.

Integer Expressions

An expression created by combining integer variables or constants by using integer


arithmetic operators is known as an integer expression. For example, consider that you
have an integer constant, RATE, with value 10 and integer variables, Area and Cost. If
Area has the value 25, then the following expression will be an integer expression:
Cost = Rate * Area

The result of an integer expression will always be an integer. Consider that you have a, b,
and c as integer variables and d as integer constant.

4.12 Operators and Decision-Making Constructs


Each of the following expressions combines one or more of these variables and constants
with integer arithmetic operators, thereby, forming integer expressions:
 -a
 a/b * c
 b%d
 a + b – c/d

Real Expressions

An expression created by combining real variables or constants by using real arithmetic


operators is known as a real expression. For example, if you have a float constant, PI,
with value 3.14 and float variable Radius with value 4.5, then the following expression
will be a real expression:
PI * radius * radius

Logical Expressions
An expression that evaluates to either true or false is known as a logical expression. You
can form a logical expression by combining constants or variables by using relational or
logical operators. The following statements are examples of logical expressions:
1. a > b
2. (a – b) < d && (c + a) < b
3. (a > b) || (b > c)
4. (a<= b) && (d<=c)

Note
An expression that is formed by combining integer variables/constants with real
variables/constants by using arithmetic operators is known as compound or
mixed-mode expression.

Operators and Decision-Making Constructs 4.13


Type Conversion

There may be situations where you need to use constants or variables of one type with
those of some other types in an expression. In such a scenario, the result of the expression
is converted into the type of variable to which the result is being stored.

This process of conversion of one type into a different type is referred to as type
conversion. C++ provides the following two methods of type conversions:
 Implicit type conversion: This form of conversion does not require any intervention
by the programmer. It is performed implicitly by the compiler. Relying on implicit
type conversion may result in loss of data in case a higher data type is converted into
a lower data type.
 Explicit type conversion: This form of conversion forces the compiler to convert
one data type into a specified data type. In C++, you can explicitly convert an
expression into a specific type by using type casting, which has the following syntax:
result = (type) expression;

In the above syntax, type represents the data type in which you want the result of the
expression to be converted to. This result will then be stored in the result on the left
side of the assignment operator (=).
Consider the following statement:
int x = 5.5/2;

In the above statement, the expression on the right evaluates to a decimal value and
the expression on the left is an integer and hence, cannot hold a fraction. An analogy
would be excessive amount of tea poured into a tea cup. Data can be lost when the
expression is converted from a higher data type to a lower data type.
You can also explicitly typecast the preceding assignment, as shown in the following
statement:
int x = (int)5.5 / 2;

Similarly, consider the following example:


char ch=’Z’;
cout<<(int)ch;

Here, the generated output will be 90, which is the ASCII value of Z.
Consider the following statement that shows implicit type conversion:
int var1;
var1=19.99 + 11.99; //Value stored in var1 is 31

4.14 Operators and Decision-Making Constructs


When the above statement is executed, the compiler first adds the two double values,
then converts the result to int. C++ does such implicit type conversion
automatically. The following table lists some of the potential problems encountered
due to implicit typecasting.

Data type Converted to Result

double float Loss of precision. If the converted value is


out of the float range, the result is
undefined.

float Int Loss of fractional part. If the converted


value is out of the integer range, the result
is undefined.

long short If the converted value is out of the short


range, only the lower order bytes are
copied.

Potential Problems due to Implicit Type Conversion

Operators and Decision-Making Constructs 4.15


Conditional Constructs
The ability to make decisions is fundamental to human beings. Decision-making can be
incorporated into programs as well. The result of which determines the sequence in which
a program will execute instructions. You can control the flow of a program by using
conditional constructs. Conditional constructs allow the selective execution of statements,
depending on the value of the expressions associated with them. The comparison operators
are required for evaluating the conditions.

The if...else Construct

The if conditional construct is followed by a logical expression where data is compared


and a decision is made based on the result of the comparison.

The syntax for the if...else construct is:


if (expression)
{
statements;
}
else
{
statements;
}

Consider the following program:


#include <iostream>
class constructs
{
char chr;
public:
void acceptCharacter( )
{
cout << "Enter a character: ";
cin >> chr;
if(chr == 'A')
cout << endl << "The character is A";
else
cout << endl << "The character is not A";
}
};

4.16 Operators and Decision-Making Constructs


int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}

Note
The operator ==, which is used for comparing two data items, is different from the
assignment operator =.

In an if...else block of statements, the condition is evaluated first. If the condition is


true (value is non-zero), the statements in the immediate block are executed, if the
condition is false (value is zero) the statements in the else block are executed.

In the above example, if the input character is 'A', the message, The character is A, is
displayed or else the message, The character is not A, is displayed. In addition, note
that the condition has to be specified within parenthesis.

If however, the = operator is used instead of the == operator, the statement is executed as
an assignment. For example, if the statement if(chr == 'A') is written as if(chr =
'A') then, chr would be assigned the value 'A' and the condition will be evaluated as
true. Thus, the message The character is A will be displayed, regardless of the input.

Conditional Operator
Consider the following if...else statements:
if ( iNum1 > iNum2 )
{
iMax = iNum1;
}
else
{
iMax = iNum2;
}

In the above program code, iMax is assigned the value iNum1 if the test expression is true,
and is assigned the value iNum2 if the test expression is false.

Operators and Decision-Making Constructs 4.17


The above program code can be modified by using the conditional operator as:
iMax = ( iNum1 > iNum2 ) ? iNum1 : iNum2;

The ?: operator is called the conditional (or the ternary) operator and takes the form:
Exp1 ? Exp2: Exp3;
where, Exp1, Exp2, and Exp3 are expressions. Exp1 is evaluated. If it is true, Exp2
becomes the value of the expression, and if false, Exp3 becomes the value of the
expression. For example, in the following statement:
iVar1=10;
iVar2 = (iVar1 > 9) ? 30 : 40;

iVar2 will be assigned the value 30. If iVar1 is less than or equal to 9, then iVar2 will
receive the value 40.

You can also use a nested if...else construct in your program. In a nested if...else
construct, you can have an if...else construct inside another if...else construct. The
following program uses a nested if...else construct to check if the input character is
uppercase or lowercase:
#include <iostream>
class constructs
{
char inp;
public:

void acceptCharacter( )
{
cout << "Enter a character: ";
cin >> inp;
if(inp >= 'A')
if(inp <= 'Z')
cout << endl << "Uppercase";
else if (inp >= 'a')
if(inp <= 'z')
cout << endl << "Lowercase";
else
cout << endl << "Input character > z";
else
cout << endl << "Input character > Z but less than a";
else
cout << endl << "Input character less than A";
}
};
int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}

4.18 Operators and Decision-Making Constructs


In the above program, note how the statements are neatly indented. This helps in
enhancing the readability of functions. In C++, you can write a complete program in a
single line, which may be compiled and executed, but it will not be readable.

The following program shows how the clarity of steps can be increased by using braces
({ and }) for enclosing parts of the code that follow an if or an else statement:

#include <iostream>
class constructs
{
char inp;
public:

void acceptCharacter( )
{
cout << "Enter a character: ";
cin >> inp;
if(inp >= 'A')
{
if(inp <= 'Z')
{
cout << endl << "Uppercase";
}
else if (inp >= 'a')
{
if(inp <= 'z')
{
cout << endl << "Lowercase";
}
}
}
}
};
int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}

Braces are mandatory when multiple steps are to be executed, corresponding to an if or


else statement.

The following program uses a cascading if...else construct to determine if the input
character is a vowel, else it prints an appropriate message:
#include <iostream>
class constructs
{
char in_chr;
public:

Operators and Decision-Making Constructs 4.19


void acceptCharacter( )
{
cout << "Enter a character in lowercase" << endl;
cin >> in_chr;
if(in_chr == 'a')
cout << endl << "Vowel a" << endl;
else if(in_chr == 'e')
cout << endl << "Vowel e" << endl;
else if(in_chr == 'i')
cout << endl << "Vowel i" << endl;
else if(in_chr == 'o')
cout << endl << "Vowel o" << endl;
else if(in_chr == 'u')
cout << endl << "Vowel u" << endl;
else
cout << endl << "The character is not a vowel" << endl;
}
};
int main()
{
constructs c1;
c1.acceptCharacter();
return 0;
}

The output of this program for two different character inputs is shown below:
Enter a character in lowercase
e

Vowel e

Enter a character in lowercase


p
The character is not a vowel

The switch...case Construct

Another conditional construct available in C++ is, switch...case. It is used when there
are multiple values for a variable. When the switch statement is executed, its
condition-variable is evaluated and compared with each case constant. If one of the case
constants is equal to the value of the condition-variable, control is passed to the statement
following the matched case label. If no case constant matches the condition-variable, and
there is a default label, control passes to the statement with the label default. If no
case matches and if there is no default label, then none of the statements in the switch
is executed. A break statement is used to exit the switch statement.

4.20 Operators and Decision-Making Constructs


The switch...case construct has the following syntax:
switch (variable_name)
{
case constant_expression_1:
statements;
break;
case constant_expression_2:
statements;
break;

case constant_expression_n:
statements;
break;
default:
statements;
}

The keyword switch is followed by the variable in parentheses, as shown below:


switch(x)

Each case keyword is followed by a case constant, as shown below:


case 1:

The data type of the case constant should match with that of the switch variable. Before
entering the switch construct, a value should be assigned to the switch variable.

The break Statement


The break statement, when used in the switch...case construct, causes the program
flow to exit the body of the switch construct. Control passes to the first statement
following the end of the switch construct. If the break statement is not used, the control
passes to the next case statement and the remaining statements in the switch construct
are executed.

The default Keyword


The statements associated with the default keyword are executed if the value of the
switch variable does not match any of the case constants.

Note
Both, case and default, statements may occur in any order. The case expressions
can be either an int or a char expression only.

Operators and Decision-Making Constructs 4.21


The following code snippet illustrates the use of a switch construct:
switch(x)
{
case 1:
y = 1;
break;
case 2:
y = 2;
break;
default:
y = 0;
}

Here, the variable y is assigned a value depending on the value of the variable x. In case x
has the value 1, the first case statement block is executed and y is assigned the value 1.
The break statement passes the program control out of the switch construct.

Note
The case constants in the switch construct cannot have the same value.

Similar to the nested if…else construct, you can also nest switch..case statements in
your code. In other words, you can place another switch..case construct within an outer
switch..case construct. Consider the following code snippet:

switch(x)
{
case 1: switch (z)
{
case 2 : mul = x * z;
break;
case 3 : mul = x * x;
}
break;
case 2:
mul = 10;
break;
default:
mul = 0;
}

In the preceding code snippet, a switch ..case construct is nested within the case 1
statement. If the value of x matches 1, another switch..case construct nested within the
outer construct is executed and the statements within the nested construct are tested for
the value of z.

4.22 Operators and Decision-Making Constructs


Loop Constructs
A loop is a construct that causes a section of a program to be repeated a certain number of
times. The repetition continues while the condition set for the loop remains true. When
the condition becomes false, the loop ends and the control is passed to the statement
following the loop.

The while Loop

The while loop is a looping construct available in C++. The while loop continues until
the evaluating condition/expression becomes false. The evaluating condition has to be a
logical expression and must return either a true or a false value. The variable that is
checked in the Boolean expression is called the loop control variable.

The while loop has the following syntax:


while (expression)
{
statements;
}

Consider a Fibonacci series. In a Fibonacci series, each number is the sum of its two
preceding numbers. The series starts with 1. The following program generates a Fibonacci
series between 1 and 200:
#include <iostream>
class loops
{
int num1;
int num2;
public:
void fibonacci()
{
num1=num2=1;
cout << num1 << endl;
while (num2 < 200)
{
cout << num2 << endl;
num2 += num1;
num1 = num2 – num1;
}
}
};

Operators and Decision-Making Constructs 4.23


int main()
{
loops L1;
L1.fibonacci();
return 0;
}

Output
1
1
2
3
5
8
13
21
34
55
89
144

Note that in the preceding output, each number in the series is the sum of the two
preceding numbers.

The break Statement


The break statement causes the program flow to exit the body of the while loop. The
following program code illustrates the use of the break statement:
#include <iostream>
class loops
{
int num1;
int num2;
public:
void fibonacci()
{
num1=num2=1;
cout << num1 << endl;
while (num2 < 150)
{
cout << num2 << endl;
num2 += num1;
num1 = num2 - num1;
if (num2 == 89)
break;
}
}
};

4.24 Operators and Decision-Making Constructs


int main()
{
loops L1;
L1.fibonacci();
return 0;
}

The output of this program is:


1
1
2
3
5
8
13
21
34
55

The control exits the loop when the condition num2 == 89, becomes true.

The continue Statement


The continue statement returns the control to the beginning of the while loop, skipping
any statement following the continue statement in the loop body. The following
example illustrates the use of the continue statement:
#include <iostream>
class loops
{
int num;
char reply;
public:
void square()
{
reply='y';
while(reply!='n')
{
cout<<"Enter a number less than 100"<<endl;
cin>>num;
if(num>100)
{
cout <<"The number is greater than 100"<<endl;
continue;
}
cout<<"The square of the number is "<<num*num<<endl;
cout<<"Do you want to enter another (y/n) ";
cin>>reply;
}
}
};

Operators and Decision-Making Constructs 4.25


int main()
{
loops L1;
L1.square();
return 0;
}

The do...while Loop

The do...while loop construct is similar to the while loop construct, as both iterate until
the specified loop condition becomes false. It differs from the while loop because the
body of the do…while loop is executed at least once, and the condition is evaluated for
subsequent executions.

The difference is illustrated in the figure shown below.

do while

Execute body
of loop
Evaluate
condition
FALSE

TRUE

Evaluate
condition FALSE Execute body
of loop

while

TRUE

Difference in Execution of the do...while and while Loops

The do...while loop has the following syntax:


do
{
statements;
} while(boolean_expr);

4.26 Operators and Decision-Making Constructs


Example
num = 11;
do
{
num++;
} while (num < 10);

In the preceding example, the condition while (num < 10) is evaluated only after the
body of the loop has been executed once. Therefore, the value of num is increased by 1. If
the same code is written in a while loop, the loop will not be executed.

The for Loop Construct

The for loop construct provides a compact way of specifying the statements that control
the repetition of the steps within the loop. In the for construct, the loop control statements
are not written within the body of the loop; instead they are written at the top. This makes
the program more readable and easily understandable. The for statement consists of the
keyword for followed by parentheses containing three expressions, each separated by a
semicolon. These are the initialization expression, the test expression, and the
increment/decrement expression.

The for loop has the following syntax:


for( initialization_expr; test_expr; change_expr)
{
statements;
}

The body of the for loop is enclosed within braces. In the following statement:
for( ivar = 0; ivar <= 10; ivar++)

ivar = 0 is the initialization expression, ivar <= 10 is the test expression, and ivar++ is
the increment expression. Here, ivar is the loop variable.

Initialization Expression
The initialization expression is executed only once, when the control is passed to the loop
for the first time. It gives the loop variable an initial value.

Operators and Decision-Making Constructs 4.27


Test Expression
The condition is executed each time the control passes to the beginning of the loop. The
body of the loop is executed only after the condition has been checked. If the condition
evaluates to true, the loop is executed, otherwise the control passes to the statement
following the body of the loop.

The Increment/Decrement Expression


The increment/decrement expression is always executed when the control returns to the
beginning of the loop.

Consider the following program:


#include <iostream>
class loops
{
int var;
public:
void display()
{
for( var = 1; var <= 10; var++)
{
cout << " " << (var * var);
}
cout << endl;
}
};
int main()
{
loops L1;
L1.display();
return 0;
}

The output of the program is: 1 4 9 16 25 36 49 64 81 100

If there are multiple initializations or multiple reinitializations, they are separated by


commas in the for loop control construct. Any or all the components of the for construct
may be left blank. However, if the condition is omitted, a break statement must be
provided in the body of the loop. The program given below accepts and displays 10
numbers and is written omitting the initialization and the condition in the for loop:
#include <iostream>
// Program to accept and display 10 numbers
class loops
{
int num;
int times;
public:

4.28 Operators and Decision-Making Constructs


void display()
{
times=0;
for( ; ; times = times + 1)
{
if(times >= 10)
{
break;
}
cout << endl << "Enter a number: ";
cin >> num;
cout << endl << num;
}
}
};
int main()
{
loops L1;
L1.display();
return 0;
}

A common mistake that programmers might make is to terminate the for loop with a
semicolon. For example, check the following statements:
for( var = 0; var <= 10; var++);
{
cout << var * var;
}

The output of the above statements is 121.

Since the for statement is terminated with a semicolon, it becomes a self-executing for
loop that moves to the next statement only when the condition in the for loop becomes
false. The for loop is exited when the value of var is 11, and hence the output is 121
(11*11).

Nested Loops

Similar to the nested if…else or nested switch…case constructs, you can nest loops
within another loop. In a nested loop, the inner loop terminates before the termination of
the outer loop.

Consider the following code snippet:


#include<iostream.h>
#include <conio.h>

void main()
{

Operators and Decision-Making Constructs 4.29


clrscr();
for(int j=1; j<=4;j++)
{
cout<< "\n";
for(int i=1;i<=j;i++)
{
cout<<i;
}
}
getch();
}

In the preceding code snippet, the nested for loop is executed for each value of j. The
nested for loop is executed until i is less than or equal to the value of j. When the value
of j is 1, i is initialized with 1 and its value is displayed on the screen. The nested loop
executes only once because i is already equal to the value of j before the first iteration.

Next, when j=2, the nested loop will execute twice, that is, till the value of i becomes 2.
Similarly, the inner loop executes thrice for j=3 and four times for j=4.

The following output is generated on the execution of the preceding code:


1
12
123
1234

4.30 Operators and Decision-Making Constructs


Activity: Loop Constructs

Problem Statement 1
Write a program that will reverse an accepted string and copy it into another string.

Solution
#include <iostream>
class strings
{
char source[101], dest[101];
int pos ,j;
public:
void reverseString()
{
pos=j=0;
cout << "Enter string to be reversed"
<< " (please enter a maximum of 100 characters): " << endl;
cin >> source;
while(source[pos]!= '\0')
{
pos = pos + 1;
}
for(--pos; pos >= 0 ;dest[j++] = source[pos--]);
dest[j] = ‘\0’;
cout << endl << "The reversed string is: " << endl << dest << endl;
}
};
int main()
{
strings S1;
S1.reverseString();
return 0;
}

A sample output of the code is given below:


Enter string to be reversed (please enter a maximum of 100
characters):
Once_upon_a_time_there_lived_a_rabbit_called_SigMa123.

The reversed string is:


.321aMgiS_dellac_tibbar_a_devil_ereht_emit_a_nopu_ecnO

Operators and Decision-Making Constructs 4.31


In the preceding code, the following statements:
pos = 0;
while(source[pos]!= '\0')
{
pos = pos + 1;
}

position the variable pos at the location of the NULL character in the array named source.
This statement can also be written as:
pos = -1;
while(source[++pos]);

The statement for(--pos; pos >= 0 ;dest[j++] = source[pos--]);, first positions


the variable pos on the character just before the NULL character. Then, it copies individual
characters into the array named dest. The value of the variable pos is decreased to
traverse the array dest from the end to the start. It can also be written as:
int j = 0;
pos = pos - 1;
while (pos >= 0)
{
dest[j] = source[pos];
j = j + 1;
pos = pos – 1;
}

The statement, dest[j] = ‘\0’;, is required because the array must terminate with a
NULL character.

Problem Statement 2
Write a program to accept and display the amount outstanding for 10 customers. The
amount outstanding should be displayed in an ascending order.

Solution
In this program, to sort the float array in ascending order, you need to perform the
following steps:
1. Traverse the array.
2. Compare the value of the current element with the value of the next element for each
element in the array.

4.32 Operators and Decision-Making Constructs


3. Perform a swap operation if the value of the current element is greater than that of
the next element, and then restart the traversal.
4. If the value of the current element is greater than that of the next element in the
array, swap the values. Restart the traversal.
5. Repeat steps 1 to 3 nine times.

The following program accomplishes the required task:


#include <iostream>
class Customers
{

float amounts[10];
public:

void sortData()
{
int ctr;
for ( ctr = 0; ctr < 10; ctr ++ )
{
cout << “Enter the amount : ";
cin >> amounts[ctr];
}
int counter=0;
/* Traverse the array */
while(counter < 9)
{
float temp;
/* Compare the value of current element with the next */
if(amounts[counter] > amounts[counter + 1])
{
/* Swap the values */
temp = amounts[counter];
amounts[counter] = amounts[counter + 1];
amounts[counter + 1] = temp;
counter = 0;
continue;
}
counter++;
}
}

void display()
{
/* Display all the array elements */
for(int counter = 0;counter < 10; ++counter)
{
cout << "Element " << counter << ": " <<
amounts[counter] << endl;
}
}
};

Operators and Decision-Making Constructs 4.33


int main()
{
Customers C1;
C1.sortData();
C1.display();
return 0;
}

Problem Statement 3
Write a program to convert upper-case characters in a sentence into lower-case characters.

Solution
// Program to convert case,
/*function to convert a string to lower-case*/
#include<stdio.h>
#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
char in_str[101];
int i=0;
printf("Enter a string (upto 100 characters)\n");
gets(in_str);
while(in_str[i]!='\0')
{
if(in_str[i]>='A' && in_str[i]<'Z') /*check for upper-
case letters*/
in_str[i]=in_str[i]+32;
i=i+1;
}
cout<<"The converted string is"<< in_str;
getch();
}

4.34 Operators and Decision-Making Constructs


The Scope of a Variable
Every variable has an associated scope. The scope defines the visibility of the variable. In
others words, the scope of a variable specifies where it may be accessed. C++ features
three types of scopes:
 File
 Local
 Class

File Scope

File scope is considered to be the outermost scope. It is defined as "the space outside all
functions". Variables that have file scope are accessible throughout the program file and
are called global variables.

Global variables can also be referred as extern. Consider the following code snippet
given in the file J1.cpp:
#include <iostream>
#include “C:\myprograms\j2.cpp”
int i=10;
void main()
{
void disp();
i=i+9;
cout<<"J1.cpp ->"<<i;
disp();
}

To access the variable i from another file J1.cpp, it should be referred to as extern in file
j2.cpp. The following example shows the contents of j2.cpp file:
#include <iostream>
extern int i;
void disp()
{
i=i-3;
cout<<" j2.cpp->"<<i;
}

On compilation and execution of j1.cpp file, the global variable i defined in the J1.cpp
file is accessible to file J2.cpp.

Operators and Decision-Making Constructs 4.35


The following output is generated on compilation and execution of j1.cpp file:
j1.cpp 19
j2.cpp 16

Note
You can include code of one file in another file by using the following syntax in the file
where the inclusion needs to be done:

#include “filepath/filename”

However, you need to ensure that the program that finally gets executed contains only
one main() function. The program should not have another main() as a result of
multiple inclusions.

Local Scope

Local scope is defined as being limited to the braces of a function or a control structure
like for, while, and if. The variables that have local scope are not accessible outside the
function or the control structure. Such variables are called local variables. The following
program shows an example of local and global variables:
#include <iostream>
int globalVar;
class scope
{
int x;
public:
void func1()
{
int localVar=10; //localVar can be accessed only in
//func1()
cout<<globalVar<<endl; // globalVar can be accessed
//here
}
void func2()
{
cout<<localVar<<endl; //Error! LocalVar is no longer
//accessible
//localVar is out of scope.
}
};

4.36 Operators and Decision-Making Constructs


int main()
{
globalVar = 6; //globalVar can also be accessed here without
//defining
cout<<globalVar<<endl;
scope S1;
S1.func1();
S1.func2();
return 0;
}

Class Scope

When a class declaration is employed, all the members are accessible only within the
class. In other words, the member variables and functions within the class declaration will
no longer be visible to the functions outside it. The member variables and the functions in
this case are said to have class scope since their accessibility is restricted to the class.

C++ offers you the flexibility of deciding which member variables or functions should be
accessible outside the class. Declaring a member of a class as a public member enables
this. Shown below is the class declaration point, which illustrates the class scope of
member variables and functions:
class point
{
private:
int x_co_ord;
int y_co_ord;
public: // Private section ends here and public
// starts here.
// All preceding entries are not
// accessible by a variable
// of the type point. They can be
// manipulated only through
// functions defined in the public section
void set_point();
};
Practice Questions
1. Write a program to accept the salaries of 10 employees from the user and display
them in descending order for all the employees. If the user enters zero, the program
should display the message “The amount should be greater than zero” and accept the
value again.

Summary
In this chapter, you learned that:
 Operators are used to compute and compare values and test multiple conditions.
 You use arithmetic operators to perform arithmetic operations, such as addition,
subtraction, multiplication, and division.
 You can also use arithmetic assignment operators to perform arithmetic operations.
 The unary operators, such as the increment and decrement operators operate on one
operand.
 Comparison operators, which are also called relational operators, are used to
compare two values.
 Logical operators are used to combine two or more expressions.
 Conditional constructs are used to allow the selective execution of statements. The
conditional constructs in C++ are:
 if...else
 switch...case
 Looping constructs are used when you want a section of a program to be repeated a
certain number of times. C++ offers the following looping constructs:
 while
 do...while
 for
 The break and continue statements are used to control the program flow within a
loop.
 The scope of a variable specifies its accessibility.
 C++ features three types of scopes: file, class, and local scope.

Operators and Decision-Making Constructs 4.39


Exercises

Exercise 1
Create a menu-driven application that accepts the salaries of ten employees and displays
the following information:
 The maximum salary
 The minimum salary
 The average salary
 The number of employees whose salary is greater than 1000
 The salaries in ascending and descending orders

Hint: Create a class Employee with the following member functions:


void accept_details();
void display_max();
void display_min();
void display_avg();
void count();

Exercise 2
The following code to display the number of days in a month is very complex and
therefore you need to simplify the code and execute:
#include<iostream>
int main()
{
int month;
cout<< "Tell me a month number.";
cout<< "I will tell you the number of days in that month.";
cin>>month;
if((month==1)||(month==3)||(month==5)||(month==7)||(month==8)||(month
==10)||(month==12))
{
cout<<"Month has 31 days";
}
else
{
if((month==4)||(month==6)||(month==9)||(month==11))
{
cout<<"Month has 30 days";
}
else
{
if (month==2)
{

4.40 Operators and Decision-Making Constructs


cout<<"Month has either 28 or 29(if leap year) days."<<endl;
}
else
{
cout<<"There are only 12 months silly."<<endl;
}
}
}
}

Hint: Try using another construct.

Exercise 3
The following code prints a number less than the total number of objects created:
#include<iostream>
class CountsItself
{
static int objectCount;
int localCount;
public:
void setCount()
{
localCount=objectCount++;
}
void displayCount()
{
cout<<"Total number of objects :"<<localCount; }
};
int CountsItself::objectCount;
int main()
{
CountsItself count1, count2, count3;
count1.setCount();
count2.setCount();
count3.setCount();
count3.displayCount();
}

However, the preceding code does not execute correctly. Write and execute the correct
code.

Operators and Decision-Making Constructs 4.41


Additional Exercises

Exercise 1

Predict the output of the following code:


#include<iostream>
main()
{
int i=0;
int j=5;
for(;i<j;i++)
{
j--;
}
cout<<i<<endl;
}

Exercise 2

Identify the error in the following code:


#include<iostream>
class test
{
int var1=10;
int var2=20;
public:
void disp()
{
cout<<"var1="<<var1<<endl;
cout<<"var2="<<var2<<endl;
}
};

class sample
{
public:
void display()
{
cout<<"var1="<<var1;
cout<<"var2="<<var2;
}
};

int main()
{
sample S1;
S1.display();
}

Fix the error in the preceding code and verify the same by executing the code.
4.42 Operators and Decision-Making Constructs
Exercise 3

Consider the following program that assigns values to three different variables var1,
var2, and var3 through a member function assign():

#include<iostream>
class values
{
int var1;
int var2;
int var3;
public:
void assign()
{
var1=5;
var2=10;
var3=15;
}
void display()
{
cout<<"The value of variable1 is:"<<var1<<endl;
cout<<"The value of variable2 is:"<<var2<<endl;
cout<<"The value of variable3 is:"<<var3<<endl;
}
};

void main()
{
values V1;
V1.assign();
V1.var2=20;
V1.display();
}

The object of the class in the preceding program should change the value of variable var2
in the main() function. Make the necessary changes in the code to accomplish the same.

Exercise 4

Write a program to find the total runs scored by a player in three cricket matches. Also,
find the average of the runs scored.

Exercise 5

Write a program to find the maximum and minimum values from a set of values provided
by the user.

Operators and Decision-Making Constructs 4.43


Exercise 6

Write a program to find the number of vowels present in a line of text.

Exercise 7

Write a program to reverse a string.

4.44 Operators and Decision-Making Constructs


About Functions
CH AP T E R 5

Certain tasks are frequently required in programming. Most of the programming


languages provide built-in functions to perform such tasks. These built-in functions
enable a programmer to code quickly and efficiently.

A programmer may also come across a situation where he/she may want the users to
provide input values at the time of executing a program. This can be achieved by
implementing command line parameters in the program.

This chapter discusses how to use built-in functions in a C++ program. In addition, it
discusses how to handle command line parameters in a C++ program.

Objectives

In this chapter, you will learn to:


 Use built-in functions in a program
 Handle command line parameters in a program

Introduction to Object-Oriented Programming 1.1


Using Built-In Functions
C++ provides predefined functions to manipulate character, string, and numeric data.
Some of the character, string, and numeric functions are discussed in the following
sections.

Character Functions

You need to include the ctype.h library in the program in order to use the standard
character functions.

Function Description Syntax Example

isalpha Returns a nonzero int isalpha(int c) char c =’S’


number if the argument if(isalpha(c))
is an alphabet. Else
returns 0. cout << “Is
Alphabet”;

isalnum Returns a nonzero int isalnum(int c) char c;


number if the argument cin >> c;
is an alphanumeric value
(letter or character). if(isalnum(c))
Else, returns 0. cout << “Is
alphanumeric”;

isdigit Returns a nonzero int isdigit(int c) char c;


number if the argument cin >> c;
is a digit. Else returns 0.
if(isdigit(c))
cout << “Is a
digit”;

toupper Returns the uppercase int toupper(int c) char c = ‘z’;


equivalent of the letter cout << toupper(c);
received as argument.

tolower Returns the lowercase int tolower(int c) char c = ‘z’;


equivalent of the letter cout << tolower(c);
received as argument.

More About Functions 5.3


Function Description Syntax Example

isupper Returns a nonzero int isupper(int c) char c=’A’


number if the argument if isupper(c)
is in upper case. Else
returns 0. cout << “In lower
case”;

islower Returns a nonzero int islower(int c) char c=’A’


number if the argument if islower(c)
is in lower case. Else
returns 0. cout << “In lower
case”;

The following code uses the isalnum function:


#include <iostream.h>
#include <conio.h>
#include <ctype.h>

void main()
{
clrscr();
char ch=’%’;
if(isalnum(ch))
cout<< "is alphanumeric";
else
cout<< "is not alphanumeric";
getch();
}

Further, the following code uses the isalpha function:


#include <iostream.h>
#include <conio.h>
#include <ctype.h>
void main()
{
clrscr();
char ch = '1';
if(isalpha(ch))
{
cout<< "is a letter" <<endl;
cout << ch <<endl;
}
else
{
cout<< "is not a letter " <<endl;
cout << ch <<endl;
}
getch();
}

5.4 More About Functions


String Functions

You need to include the string.h library in the program in order to use the standard
string-handling functions.

Function Description Syntax Example

strcpy Copies the contents of char * strcpy ( char strcpy(cStr1,“Judas


the second string to the * dest, const char * Priest”);
first string. src );
will copy the string “Judas
Where: Priest” to the array cStr1.
dest refers to the string
where contents of string src
will get copied.

strcat Joins (concatenate) the char * strcat ( char strcat(cStr1, “ABC”);


second string with the * dest, const char *
src ); will add the string “ABC” to
first string.
the current contents of the
Where: array cStr1.
dest refers to the string
where contents of string
src will get appended.

strncpy Copies the specified char * strncpy strncpy(cStr1,“Judas


number of characters of Priest”,5);
(char * dest, const
the second string to the char * src, sizet_t will copy the string “Judas”
first string. num ); to the array cStr1.
Where:
num refers to the number of
characters that needs to be
copied from the src string
to the dest string.

strlen Returns the length for the int strlen (const If the array cStr1 contains
string. The length does char * str1 ); the string “Normal is boring”,
not include the NULL Where: then the following statement:
character.
iNum=strlen(cStr1);
str1 refers to string whose
length needs to be will cause iNum to have the
determined. value 16.

More About Functions 5.5


Function Description Syntax Example

strstr Scans string1 for the first char * strstr (char * char str1[]=”Hello
occurrence of string2. string1, const char * World”;
This function returns the string2 );
char str2[]=”or”;
offset of one string within Where:
another. char
string2 refers to string *sFound=strstr(str1,st
that needs to be searched r2);
for in string1. cout<<sFound-str1+1;

will display 8.

strcmp Compares two strings int strcmp (char * iNum=strcmp(“madonna”,


(supplied as its string1, char * ”maradona”);
parameters) and returns string2 );
will return -14(ASCII
an integer value. Where: difference of ‘d’ and ‘r’)
If the first string string1 and string2 and
argument is less than the refer to the strings that need
second, strcmp() iNum=strcmp(“ABC”,”ABC
to be compared.
returns a value less than ”);
zero. If the first argument will return zero
is equal to the second,
the function returns a and
value equal to zero. If the
iNum=strcmp(“veronica”
first argument is greater ,”Betty”);
than the second, the
function returns a value will return 52 (ASCII
greater than zero. difference of ‘v’ and ‘B’)
The value returned by
strcmp() is the
difference between the
ASCII values of the
unequal characters.

strcmpi Compares two strings int strcmpi(char * char *s1=”ABC”,


without checking for case s1, char *s2) *s2=”abc”;
differences. cout<<strcmpi(s1, s2);
Where s1 and s2 are the
strings being compared will return 0.

5.6 More About Functions


Function Description Syntax Example

strchr Searches for a character char * strchr (const ptr = strchr( s, '\0'
in a string. char * string, int );
c);
The '\0' symbol that terminates
Where: the string is also considered
part of the string; thus it is
string refers to string that
possible to find the end of the
needs to be searched for string with the preceding
character c. example

The following code uses some of the preceding string-handling functions:


#include <iostream.h>
#include <string.h>
main()
{
char string[]="string to search";
char test[]="ing";
char *ptr;
char str1[20]="Don";
char str2[20]=" Allen";
int mLength;
int mReturn;

if (strstr(string, test)) cout<<"String found";


/* strcpy copies one string into another */
strcpy(str1, str2);
cout<<endl<<"Contents of str1 is :"<<str1;
strcpy(str1,"C language");
cout<<endl<<"Final Contents of str1 is: "<<str1;
/* strlen displays the length of the string */
mLength=strlen(str1);
cout<<endl<<"The length of str1 is : "<<mLength;
/* strcmp compares two strings */
mReturn=strcmp(str1, str2);
if (mReturn == 0)
{
cout<<endl<<"The strings match";
}
else
{
cout<<endl<<"The strings do not match";
}
}

More About Functions 5.7


Note
In the preceding string functions, the’ *’ symbol is used to declare a pointer variable. A
pointer is a special type of variable that allows direct access to individual bytes in the
memory. Further, it allows the program to allocate memory the variables dynamically
(at run time). You will learn more about pointers in the subsequent chapters.

Numeric Functions

You need to include the math.h library in the program in order to use the standard
numeric functions. Whereas, in case of the abs and atoi function you include the
stdlib.h library file.

Function Description Syntax Example

abs Returns the absolute value int abs ( int n ); abs(-2)


of the integer parameter.
where n refers to the will return 2 in the
integer whose absolute result variable
value needs to be returned.

ceil Rounds up the parameter int ceil ( int n ); ceil(1.4)


to the nearest integer
where n refers to the will return 2 in the
value.
integer of which the nearest result variable
integer value is returned.

floor Returns the largest integer double floor(double floor(1.8)


that is less than or equal x );
will return 1 in the
to the integer passed as a where x refers to a floating result variable
parameter.
point value.

sqrt Returns the square root of double sqrt ( double param = 1024.0;
parameter. x );
result = sqrt
where x refers to the (param);
non-negative floating point will store 32 in the
value. result variable

5.8 More About Functions


Function Description Syntax Example

atoi Returns the integer value int atoi (const char Char
stored as a string. * string); str[]=”345A”;

where string refers to the result=atoi(str);


string containing the
will store 345 in the
integer value.
result variable

randomize Initializes the random void randomize(); randomize();


number generator with a
random number. It is used
with the random()
function, If the
randomize() function is
not used, then the
random() function will
always return the same
value on each execution.

random Returns a randomly int random (int randomize();


generated number number);
cout<<
between 0 and number. random(500);
where number refers to the
value till which the random
will return any value
number needs to be
between 0-500
generated.

sin Accepts an angle in radian double sin(double sin(45);


as parameter and returns x);
will return the sine
the trigonometric sine of
where x is the angle whose value of 45, which is
the angle.
sine needs to be returned. 0.850904

cos Accepts an angle in radian double cos(double cos(30);


as parameter and returns x);
will return the cosine
the trigonometric cosine
where x is the angle whose value of 30, which is
of the angle.
cosine needs to be returned. 0.154251

fabs Returns the absolute value double fabs (double fabs(-2.0);


of its parameter. x);
will return 2.0
where x is the positive or
negative number whose
absolute value needs to be
returned.

More About Functions 5.9


Function Description Syntax Example

log Returns the natural double log (double log(10.0);


logarithm for its x);
will return the natural
parameter.
where x is the parameter logarithm value of
whose natural logarithm 10.0, which is
needs to be returned. 2.302585

log10 Returns the base 10 double log10(double log10(10.0);


logarithm for its x);
will return the base 10
parameter.
where x is the parameter logarithm for 10.0,
whose base 10 logarithm which is 1
value needs to be returned.

pow Returns base raised to double pow(double pow(5.0, 2.0);


exponential power. base, double e) ;
will return the value of
where the base parameter 5 raised to the power
needs to be raised to the e of 2, which is 25
parameter.

The following code uses some of the preceding numeric functions:


#include <iostream.h>
#include <math.h>

main()
{
double a=3.9;
double b=2.3;
int x;

x=floor(a);
cout<<endl<<"The floor value of a is: "<<x;
x=floor(b);
cout<<endl<<"The floor value of b is: "<< x;
x=ceil(a);
cout<<endl<<"The ceil value of a is: "<< x;
x=ceil(b);
cout<<endl<<"The ceil value of b is: "<< x;
}

5.10 More About Functions

You might also like