Professional Documents
Culture Documents
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.
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.
Operators supported in C++ are listed below. Unary operators are used with
one operand and binary operator is used with two operands.
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
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.
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
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
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.
//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;
}
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.
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.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
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;
}