You are on page 1of 21

Object Oriented Programming – C++ Unit 1

Unit 1 Evolution of Programming Methodologies


Structure:
1.1 Introduction
1.2 Evolution of Programming Methodologies
1.3 Introduction to OOP and its basic features
1.4 Basic components of a C++ Program and program structure
1.5 Compiling and Executing C++ Program
1.6 Selection control statements in C++
1.7 Summary
1.8 Terminal Questions
1.9 Answers

1.1 Introduction
A software component is reusable if it can be used beyond its initial use
within a single application or group of applications without modification. The
programming paradigms which are most widely used and implemented by
various programming languages are Imperative programming, object
oriented programming functional programming, generic programming and
meta-programming. In this book we are going to discuss the object oriented
programming. This unit is focusing on the evolution of programming
methodologies, basic components of C+ + programming and its structure
and explores the process of compilation and execution of C++ programs.
After studying this unit you should be able to:
 explain the role of object oriented programming approach over
procedural languages
 discuss the basic features supported by OOP languages
 define the construct of a C++ program and compile and execute it.

1.2 Evolution of Programming methodologies


The programming languages have evolved from machine languages,
assembly languages to high level languages to the current age of
programming tools. While machine level language and assembly language
was difficult to learn for a layman, high level languages like C, Basic, Fortran
and the like was easy to learn with more English like keywords. These
languages were also known as procedural languages as each and every

Sikkim Manipal University Page No.: 1


Object Oriented Programming – C++ Unit 1

statement in the program had to be specified to instruct the computer to do


a specific job. The procedural languages focused on organizing program
statements into procedures or functions. Larger programs were either
broken into functions or modules which had defined purpose and interface
to other functions.
Procedural approach for programming had several problems as the size of
the software grew larger and larger. One of the main problems was data
being completely forgotten. The emphasis was on the action and the data
was only used in the entire process. Data in the program was created by
variables and if more than one functions had to access data, global
variables were used. The concept of global variables itself is a problem as it
may be accidentally modified by an undesired function. This also leads to
difficulty in debugging and modifying the program when several functions
access a particular data.
The object oriented approach overcomes this problem by modeling data and
functions together there by allowing only certain functions to access the
required data.
The procedural languages had limitations of extensibility as there was
limited support for creating user defined datatypes and defining how these
datatypes will be handled. For example if the programmer had to define his
own version of string and define how this new datatype will be manipulated,
it would be difficult. The object oriented programming provides this flexibility
through the concept of class.
Another limitation of the procedural languages is that the program model is
not closer to real world objects . For example, if you want to develop a
gaming application of car race, what data would you use and what functions
you would require is difficult questions to answer in a procedural approach.
The object oriented approach solves this further by conceptualizing the
problem as group of objects which have their own specific data and
functionality. In the car game example, we would create several objects
such as player, car, traffic signal and so on.
Some of the languages that use object oriented programming approach are
C++, Java, Csharp, Smalltalk etc. We will be learning C++ in this text to

Sikkim Manipal University Page No.: 2


Object Oriented Programming – C++ Unit 1

understand object oriented programming. C++ is a superset of C. Several


features are similar in C and C++.
Self Assessment Questions
1. List the limitations of procedural languages
2. _______ is an OOP Language
3. In OOP approach programmers can create their own data types.
True/False
4. In procedural languages, the programs are written by dividing the
programs into smaller units known as __________

1.3 Introduction to OOP and its basic features


As discussed earlier, one of the basic concept in Object Oriented
Programming approach is bundling both data and functions into one unit
known as object. The functions of a particular object can only access the
data in the object providing high level of security for the data. The functions
in the object are known as member functions or sometimes as methods.
The key features of OOP programming languages are:
 Objects and Classes
An Object is a program representation of some real-world thing
(i.e person, place or an event). Objects can have both attributes(data)
and behaviours (functions or methods). Attributes describe the object
with respect to certain parameters and Behaviour or functions describe
the functionality of the object.
Table 1.1 Example of Objects
Polygon Object Bank Account
Attributes Behaviour Attributes Behaviour
Position Move Account Deduct Funds
Fill Color Erase number Transferfunds
Border color Changecolor Balance DepositFunds
Showbalance

According to Pressman, Objects can be any one of the following:


a) External entities
b) Things
c) Occurrences or events

Sikkim Manipal University Page No.: 3


Object Oriented Programming – C++ Unit 1

d) Roles
e) Organisational units
f) Places
g) Data Structures
For example, objects can be an menu or button in an graphic user interface
program or it may be an employee in an payroll application. Objects can
also represent a data structure such as a stack or a linked list. It may be a
server or a client in an networking environment.
Objects with the same data structure and behavior are grouped together as
class. In other words, Objects are “instances” of a class. Classes are
templates that provide definition to the objects of similar type. Objects are
like variables created whenever necessary in the program. For example,
Employee may be a class and Pawan, Sujay and Ganesh are objects of the
class employees. Just as you can create as many variables of a default
datatype such as integer, you can create as many objects of a class.
Classes and Objects support data encapsulation and data hiding which are
key terms describing object oriented programming languages. Data and
functions are said to be encapsulated in an single entity as object. The data
is said to be hidden thus not allowing accidental modification.
 Inheritance
Inheritance is one of the most powerful feature of Object Oriented
Programming Languages that allows you to derive a class from an
existing class and inherit all the characteristics and behaviour of the
parent class. This feature allows easy modification of existing code and
also reuse code. The ability to reuse components of a program is an
important feature for any programming language
 Polymorphism and Overloading
Operator overloading feature allows users to define how basic operators
work with objects. The operator + will be adding two numbers when
used with integer variables. However when used with user defined string
class, + operator may concatenate two strings. Similarly same functions
with same function name can perform different actions depending upon
which object calls the function. This feature of C++ where same
operators or functions behave differently depending upon what they are
operating on is called as polymorphism (Same thing with different forms).
Operator overloading is a kind of polymorphism.

Sikkim Manipal University Page No.: 4


Object Oriented Programming – C++ Unit 1

OOP approach offers several advantages to the programmers such as


 Code can be reused in situations requiring customization
 Program modeling and development closer to real world situations and
objects
 Easy to modify code
 Only required data binded to operations thus hiding data from unrelated
functions
Self Assessment Questions
5. _____________ feature in OOP allows to reuse code.
6. The concept of bundling data and functions into single unit is termed as
___________
7. Object is an __________ of a class
8. Give an example of a class and an object
9. ______________ is an advantage of OOP approach

1.4 Basic components of a C++ Program and program structure


The C++ is a superset of C. At the basic level, the programs look similar in
both C and C++. Every statement in C++ ends with a semicolon (;). All the
reserved words have to be written in small case and the c++ compiler is
case sensitive. Data in programming languages are stored in variables. To
create a variable, the variable should support an inbuilt datatype. The
variable is a name given to a particular location in the memory and the value
stored in a variable can be altered during program execution. The datatypes
supported in C++ are listed below:
Table 1.2 Basic Datatypes in c++
Data Type Size (in bytes) Values that can be taken
Int 2 -32768 to 32767
Bool 1 False and true / 0 and 1
Char 1 -128 to 127
Long 4 -2,147,483,648 to 2,147,483,647
-38 38
Float 4 3.4 X 10 to 3.4 X 10 (Precision 7)
-308 308
Double 8 1.7 X 10 to 1.7 X 10 (Precision 15)
-4932 4932
Long double 10 3.4 X 10 to 1.1 X 10 (Precision 19)
Unsigned int 2 0 to 65,535

Sikkim Manipal University Page No.: 5


Object Oriented Programming – C++ Unit 1

Variables can be named according to following rules


 Can comprise of 1 to 8 alphabets, digits or underscore
 First character should be an alphabet
 Names are case sensitive
 Reserve words of c++ cannot be used
Variables have to be declared before using them in the program. The
declaration is done in the following way:
datatype variablename
Eg: int data ;
The above declaration declares a integer variable named data. The value
stored in int data by default is a junk value. Values can also be assigned to
the variable during declarations or initialized separately using the
assignment operator =.
Eg: int data=0;
Or
int data;
data=0;
Constants are those which do not change during execution of a program.
The constants in C++ can be numeric, character or string constants.
Examples of each are shown in table 1.3
Table 1.3 Example of Constants
Constant Example Constraints
Numeric 23000 Can be negative or positive, cannot
Constant 450.6 (Floating point) contain blanks or commas, or $

Character ‘A’ Any character enclosed within single


Constant quotes, represented by unique ASCII
number in the memory
String Constant “Hello” Set of characters enclosed in double
quotes, last character in the string is
null character ‘\0’

Operators supported in C++ are listed below. Unary operators are used with
one operand and binary operator is used with two operands.

Sikkim Manipal University Page No.: 6


Object Oriented Programming – C++ Unit 1

Table 1.4 Operators in C++


Arithmetic Operators Type Action
- Unary as Subtraction for binary and minus for
well as unary
binary
+ Binary Addition
* Binary Multiplication
/ Binary Division
% Binary Modulus (remainder after dividing)
-- Unary Decrement value by one
++ Unary Increment value by one
Relational Operators Type Action
> Binary Greater than
>= Binary Greater than or equal
< Binary Less than
<= Binary Less than equal
== Binary Comparision for equality
!= Binary Comparision for inequality
Logical Operators Type Action
&& Binary AND
|| Binary OR
! Unary NOT

Lets begin with a simple c++ program


// sum.cpp
#include<iostream.h>
void main()
{
int a,b,sum;
cout<<”Please enter any two numbers”<<endl;

Sikkim Manipal University Page No.: 7


Object Oriented Programming – C++ Unit 1

cin>>a>>b;
sum=a+b;
cout<<”Sum of two numbers is ”<<sum;
}
The above program asks the user to enter two numbers and displays the
sum of the two numbers. Iostream.h is a header file. The first statement of
the above program is required if you would like to include the cin and cout
statements which is used for standard input or input from keyboard and
standard output or output to display screen. cin and cout are actually
predefined objects in C++. Iostream.h file contains the declarations for using
the cin and cout statements. There are several such header files which have
to be included depending on the functions you are using. We will come
across many such header files as we progress.
Every C++ program should have a main() function. C++ allows you to create
your own functions in the program, like C. However the program execution
always begins with the master function main(). Paranthesis are used to
group statements belonging to one function or program statement. Every
opening parathesis ({ ) should have a matching closing parathesis ( }).
The third statement declares three integer variables a, b and sum. The
fourth statement displays “Please enter any two numbers” on the display
screen using cout statement. Cout (pronounced as C out) uses << or
insertion operator to push data to the output stream.
Operators known as manipulators can be used along with the << operator to
modify the way data is displayed. Endl is an operator which is similar to ‘\n’
character in C that inserts a linefeed into the output. The first cout statement
in the program displays a statement where as the second cout statement
displays a statement and the value stored in the variable sum.
Cin (pronounced as c in) statement uses >> or extraction operator to feed
the data to the input stream. The above cin statement waits for user to enter
two integers. The values entered by the user is then stored in the variables
a and b. Each variable in cin statement should separated by >> operator.
Comment statements can be included in the program by prefixing the
statement with “//” for single line comments. Comments add clarity to the

Sikkim Manipal University Page No.: 8


Object Oriented Programming – C++ Unit 1

program. Multiple line comments can be added by enclosing the statements


between /* and */.
Self Assessment Questions
10. ______________ is a header file used in c++ that handles input and
output functions.
11. ____________ statement is used to input data from the user in c++.
12. ______________ statement is used to display data on the display
screen in c++.
13. ______________ is a master function required in all C++ program and
program execution begins from the first statement of this function.

1.5 Compiling and Executing C++ Program


There are three steps in executing a c++ program: Compiling, Linking and
Running the program. The c++ programs have to be typed in a compiler. All
the programs discussed in the book will be compiled on turbo c++ compiler.
The turbo c++ compiler comes with an editor to type and edit c++ program.
After typing the program the file is saved with an extension .cpp. This is
known as source code. The source code has to be converted to an object
code which is understandable by the machine. This process is known as
compiling the program. You can compile your program by selecting compile
from compile menu or press Alt+f9. After compiling a file with the same
name as source code file but with extension .obj. is created.
Second step is linking the program which creates an executable file .exe
(filename same as source code) after linking the object code and the library
files (cs.lib) required for the program. In a simple program, linking process
may involve one object file and one library file. However in a project, there
may be several smaller programs. The object codes of these programs and
the library files are linked to create a single executable file. Third and the
last step is running the executable file where the statements in the program
will be executed one by one.
Fig 1.1 shows the entire process. When you execute the program, the
compiler displays the output of the program and comes back to the program
editor. To view the output and wait for user to press any key to return to the
editor, type getch() as the last statement in the program. Getch() is an inbuilt
predefined library function which inputs a character from the user through

Sikkim Manipal University Page No.: 9


Object Oriented Programming – C++ Unit 1

standard input. However you should include another header file named
conio.h to use this function. Conio.h contains the necessary declarations for
using this function. The include statement will be similar to iostream.h.

Fig. 1.1: Compiling and Linking

During compilation, if there are any errors that will be listing by the compiler.
The errors may be any one of the following:
1. Syntax error
This error occurs due to mistake in writing the syntax of a c++ statement
or wrong use of reserved words, improper variable names, using
variables without declaration etc. Examples are : missing semi colon or
paranthesis, type integer for int datatype etc. Appropriate error message
and the statement number will be displayed. You can see the statement
and make correction to the program file, save and recompile it.
2. Logical error
This error occurs due to the flaw in the logic. This will not be identified by
the compiler. However it can be traced using the debug tool in the editor.
First identify the variable which you suspect creating the error and add
them to watch list by selecting Debug ->Watches->Add watch. Write the
variable name in the watch expression. After adding all the variables
required to the watch list, go to the statement from where you want to
observe. If you are not sure, you can go to the first statement of the
program. Then select Debug ->Toggle Breakpoint (or press ctrl + f8). A

Sikkim Manipal University Page No.: 10


Object Oriented Programming – C++ Unit 1

red line will appear on the statement. Then Run the program by
selecting Ctrl + f9 or Run option from run menu. The execution will halt
at the statement where you had added the breakpoint. The watch
variables and their values at that point of time will be displayed in the
bottom in the watch window. Press F8 to execute the next statement till
you reach the end of the program. In this way you can watch closely the
values in the watch variables after execution of each and every
statement in the program. If you want to exit before execution of the last
statement press Ctrl + Break. To remove the breakpoint in the program
go to the statement where you have added breakpoint select Debug -
>Toggle Breakpoint (or press ctrl + f8). Select Debug -> watch ->remove
watches to remove the variables in the watch list. This tool helps in
knowing the values taken by the variable at each and every step. You
can compare the expected value with the actual value to identify the
error.
3. Linker error
This error occur when the files during linking are missing or mispelt
4. Runtime error
This error occurs if the programs encounters division by zero, accessing
a null pointer etc during execution of the program
Self Assessment Questions
14. ___________, ______________ and _____________ are phases in
execution of a C++ program
15. The logical error is identified by the compiler. True/False
16. ________________ is the extension of C++ program source files
17. ________________ is the extension of C++ object code

1.6 Selection control statements in C++


There are basically two types of control statements in c++ which allows the
programmer to modify the regular sequential execution of statements.They
are selection and iteration statements. The selection statements allow to
choose a set of statements for execution depending on a condition. If
statement and switch statement are two statements which allow selection in
c++. There is also an operator known as conditional operator which enables
selection.

Sikkim Manipal University Page No.: 11


Object Oriented Programming – C++ Unit 1

If statement
Syntax : if (expression or condition)
{ statement 1;
statement 2;
}
else
{ statement 3;
statement 4;
}
The expression or condition is any expression built using relational
operators which either yields true or false condition. If no relational
operators are used for comparison, then the expression will be evaluated
and zero is taken as false and non zero value is taken as true. If the
condition is true, statement1 and statement2 is executed otherwise
statement 3 and statement 4 is executed. Else part in the if statement is
optional. If there is no else part, then the next statement after the if
statement is exceuted, if the condition is false. If there is only one statement
to be executed in the if part or in the else part, braces can be omitted.
Following example program implements the if statement.
// evenodd.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int num;
cout<<”Please enter a number”<<endl;
cin>>num;
if ((num%2) == 0)
cout<<num <<” is a even number”;
Sikkim Manipal University Page No.: 12
Object Oriented Programming – C++ Unit 1

else
cout<<num <<” is a odd number”;
getch();
}
The above program accepts a number from the user and divides it by 2 and
if the remainder (remainder is obtained by modulus operator) is zero, it
displays the number is even, otherwise as odd. We make use of the
relational operator == to compare whether remainder is equal to zero or not.
Nested If statement
If statement can be nested in another if statement to check multiple
conditions.
If (condition1)
{ if (condition 2)
{ statement1;
Statement2;
}
else if (condition3)
{statement3;
}
}
else statement4;
The flowchart of the above example is shown in figure 1.2.

Sikkim Manipal University Page No.: 13


Object Oriented Programming – C++ Unit 1

Fig. 1.2: Nested If Statement

Multiple conditions can be checked using logical && operator(AND) and ||


operator (OR).
If ((condition1) && (condition2))
statement1;
else
statement2;
In the above example statement1 will be executed if both the condition1 and
condition2 are true and in all other cases statement2 will be executed.
If ((condition1 || (condition2))
statement1;
else
statement2;
In the above example statement1 will be executed if either condition1 or
condition2 are true and even if both are true. Statement2 will be executed if
both the conditions are false. The following program demonstrates the use
of && operator and nested if statement.

Sikkim Manipal University Page No.: 14


Object Oriented Programming – C++ Unit 1

//Large.cpp
# include <iostream.h>
void main()
{ int a,b,c;
cout<<”Please enter three numbers”;
cin>>a>>b>>c;
if ((a>b) && (b>c))
cout<<a<< “ is the largest number”;
else if ((b>a) && (b>c))
cout<<b<< “ is the largest number”;
else if ((c>a) && (c>b))
cout<<c<< “ is the largest number”;
}
The above program accepts three numbers from the user and displays
which is the largest number among the three.( assumption is that all the
numbers are unique, the program has to be modified if you would like to
allow same number twice)
Switch statement
Nested ifs can be confusing if the if statement is deeply nested. One
alternative to nested if is the switch statement which can be used to
increase clarity in case of checking the different values of the same variable
and execute statements accordingly.
Syntax :
Switch (variablename)
{ case value1: statement1;
break;
case value2: statement2;
break;
case value3: statement3;
break;
default: statement4;
}

Sikkim Manipal University Page No.: 15


Object Oriented Programming – C++ Unit 1

If the variable in the switch statement is equal to value1 then statement1 is


executed, if it is equal to value2 then statement2 is executed, if it is value3
then statement3 is executed. If the variable value is not in any of the cases
listed then the default case statement or statement4 is executed. The
default case specification is optional, however keeping it is a good practice.
It can also be used for displaying any error message. Each case can have
any number of statements. However every case should have a break
statement as the last statement. Break statement takes the control out of the
switch statement. The absence of the break statement can cause execution
of statements in the next case. No break is necessary for the last case. In
the above example, default case does not contain a break statement.
The flowchart for the switch statement is shown in Fig 1.3.

Fig. 1.3: Switch Statement

Sikkim Manipal University Page No.: 16


Object Oriented Programming – C++ Unit 1

The following program implements the switch statement


position.cpp
# include<iostream.h>
void main()
{ char pos;
int x=15, y=15;
cout << “ you are currently located at” <<x<<” “<<y<<endl;
cout>>”please choose the letter to move l for left, r for right, u for up and d
for down” <<endl;
cin>>pos;
switch (pos)
{ case ‘l’: x--;
break;
case ‘r’: x++;
break;
case ‘u’: y++;
break;
case ‘d’: y--;
break;
default: cout<<”You selected a wrong option”;
}
cout<<“ you are now located at” <<x<<” “<<y;
}
The above program asks the user to enter l,r,u,d for allowing him to move
left,right,up and down respectively. The position is initialised to 15 and 15
which are x and y coordinates of his position. Depending upon the what user
has selected the the x and y co-ordinates are incremented or decremented
by one(x++ is same as x=x+1). If the user types a letter other than l,r,u,d, he
Sikkim Manipal University Page No.: 17
Object Oriented Programming – C++ Unit 1

gets an error message. Since the switch variable is a character, l,u,r,d and
enclosed within single quote.
++ and -- operator can be used as postfix or as prefix operator which has no
effect if used as an independent statement. However if it used as part of an
expression, the prefix operator will be operated and then the expression will
be evaluated whereas the postfix operated will be evaluated later.
For example in the statement x= a+ (b++), a will be added to b and then
stored in x and then the value of b will be incremented. If the same
expression is written as x=a+(++b), the the b will be incremented and then
added to a and stored in x.
Conditional Operator
Conditional operator (?:) is a handy operator which acts like a shortcut for if
else statement. If you had to compare two variables a and b and then
depending on which is larger, you wanted to store that variable in another
variable called large. You would do this using if else statement in the
following way:
if (a>b)
large=a;
else
large=b;
The above can be done using conditional operator in the following way:
large= (a>b) ? a : b ;
Self Assessment Questions
18. In if else statement, at any point of time statements in both the if and
else part may be executed. True/False
19. Conditional operator is an alternative to __________ statement
20. ++ operator increments the value of the operand by _________
21. The ++ operator used as postfix and prefix has the same effect. True
or False
22. Each case in switch statement should end with _________ statement.

Sikkim Manipal University Page No.: 18


Object Oriented Programming – C++ Unit 1

1.7 Summary
Object oriented Programming enables storing data and functions together
which enables hiding data from unnecessary exposure. Procedural
languages differs from the Object oriented programming in the approach
used in solving the problem. While the former focuses on organizing
programs around functions, the later focuses organizing programs around
classes. Classes allow users to define their own datatypes and functionality.
This allows extension of the basic datatypes supported by the language.
Reusability of code through inheritance allows users to use the existing
code without modifying it but also extend the functionality of the existing
code. The C++ programs are similar to C except for the object oriented
programming features. Every C++ program has a main function from where
the execution starts. C++ programs goes through two phases ie compiling
and linking before execution.

1.8 Terminal Questions


1. Which of the following is not a feature of Object Oriented Programming
a. Data encapsulation b. Inheritance c. Operator Overloading
d. Data Structure
2. Which one of the following is not an inbuilt basic datatype in c++
a. Int b. Bool c. String d.Float
3. Write a program that accepts two numbers from the user and swaps the
two numbers without using a temporary variable.
4. Write a program that accepts two numbers a and b and divides a by b
and displays the quotient and the remainder.
5. Object constitutes of ____________ and _____________

1.9 Answers
Self Assessment Questions
1. Limitations of procedural languages are no importance to data and
inability to define user defined datatypes and define functionality for
the same
2. C++, smalltalk, Java are all OOP Languages
3. True
4. Functions or procedures
5. Inheritance

Sikkim Manipal University Page No.: 19


Object Oriented Programming – C++ Unit 1

6. Data Abstraction
7. Object is an instance of a class
8. Class - car and object – Maruti 800
9. Reusability of code
10. iostream.h
11. cin
12. cout
13. main() function
14. Compiling, Linking and Running
15. False, it can assist in identifying using debug tool
16. .cpp
17. .obj
18. False
19. if statement
20. one value
21. False
22. break statement.
Terminal Questions
1. d
2. c
3. Program to swap two numbers without using a temporary variable
# include<iostream.h>
void main()
{ int num1,num2;
cout <<” enter two numbers”;
cin>> num1>>num2;
Num1=num1+num2;
Num2=num1-num2;
Num1=num1-num2;
cout<< “numbers after swapping are ”<<num1<<num2;
}

Sikkim Manipal University Page No.: 20


Object Oriented Programming – C++ Unit 1

4. Program to divide a and b and display quotient and remainder


# include<iostream.h>
void main()
{ int a,b, q, rem;
cout <<” enter two numbers”;
cin>> a>>b;
q=a/b;
r=a%b;
cout<< “Quotient = ”<<q<<endl;
cout<<”remainder=”<<r;
}
5. Data and Functions

Sikkim Manipal University Page No.: 21

You might also like