You are on page 1of 21

Unit-I

Why Object –Oriented Programming in C++ - Native types and statements – Functions and pointers
implementing ADTs in the base language
Object Oriented Concepts
Various characteristics of object oriented programming language are –
1. Data Encapsulation
2. Inheritance
3. Polymorphism
4. Dynamic Binding
5. Data Abstraction
6. Message Passing
We will understand these characteristics by understanding the basic concepts of object oriented
programming.
Objects
 Object is an instance of a class.
 Objects are basic run-time entities in object oriented programming.
 In C++ the class variables are called objects. Using objects we can access the member
variable and member function of a class.
 Object represent a person, place or any item that a program handles.
 For example – If the class is country then the objects can be India, China, Japan, U.S.A and
so on.
 A single class can create any number of objects.
Declaring Objects
 The syntax for declaring object is –
Class_Name Object_Name;
Example
Fruit f1;
For the class Fruit object f1 can be created.
Classes
 A class can be defined as an entity in which data and functions are put together.
 The concept of class is similar to the concept of structure in C.
Syntax
class name_of_class
{
private :

1
variable declarations;
function declarations;
public :
variable declarations;
function declarations;
};
Example
class rectangle
{
private :
int len,br;
public:
void get_data( );
void area( );
void print_data( );
};

Private area
Private area
is not Data members
accessible
by outsider Function members
of this class

Public area
Public area
can be Data members
accessible
by outsider Function members
of this class

Accessibility for member of class


Rules for declaring class name
1. The class name must begin with the letters, it may be followed by letters or digits or
underscore.
2. The name of the class must not be same as the keyword or reserved word.
3. The class name must contain any special characters such as ~ ! @ # $ % ^ & * ( ) { } [ ] + - |
\ /
Encapsulation
 Encapsulation means the detailed implementation of a component which can be hidden from
rest of the system.

2
 In C++ the data is encapsulated.
Definition
Encapsulation means binding of data and method together in a single entity called class. The
data inside that class is accessible by the function in the same class. It is normally not accessible
from the outside of the component.
Class

Data

Method

Method

Method

Concept of Encapsulation
Inheritance
Definition
 Inheritance is a property by which the new classes are created using the old classes. In other
words the new classes can be developed using some of the properties of old classes.
Example

Shape
draw()
resize()

Circle Line Rectangle


draw() draw() draw()
resize() resize() resize()

Square
draw()
resize()

3
Hierarchical structure of inheritance

 Inheritance support hierarchical structure.


 The old classes are referred as base classes and the new classes are referred as derived
classes. That means the derived classes inherit the properties (data and functions) of base
class.
 Here the shape is a base class from which the Circle, Line and Rectangle are the derived
classes. These classes inherit the functionality draw() and resize().
 Similarly the rectangle is a base class for the derived class square.
 Along with the derived properties the derived class can have its own properties. For example
the class Circle may have the function like background() for defining the background color.
Reusability
Definition
 Reusability means making use of existing class by adding the additional features and
capabilities within it.
 The existing class need not have to modify. This is possible by deriving a new class from the
existing class and adding the desired functionalities to this new class.
 Inheritance provides the facility of reusability.
Polymorphism
 Polymorphism means many structures.
 Definition: Polymorphism is the ability to take more than one form and refers to an
operation exhibiting different behavior in different instances (situations).
 The behavior depends on the type of data used in the operation. It plays an important role in
allowing objects with different internal structures to share the same external interface.
 Without polymorphism, one has to create separate module names for each method.
 For example the method clean is used to clean a Dish object, one that cleans a Car object,
and one that cleans a vegetable object.
 With polymorphism, you create a single “clean” method and apply it for different objects.
Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
 In Static binding which function is to be called for a particular object is determined at the
compile time. Selection of particular function for call is based on the type of formal
parameters.

4
 Definition: Dynamic binding is the runtime determination of which function to call for a
particular object of descendant class based on the type of argument.
 In dynamic binding the code associated with a given procedure call is not known until the
time of the call at run-time.
Data Abstraction
 Data abstraction means representing only essential features by hiding all the implementation
details. In C++, class is an entity used for data abstraction purpose.
Example
class Student
{
int roll;
char name[10];
public;
void input( );
void display( );
}

In main function we can access the functionalities using object. For instance
Student obj;
obj.input( );
obj.display( );

Thus only abstract representation can be presented, using class.

Difference between Encapsulation and Abstraction


S.No. Data encapsulation Data abstraction
1 It is a process of binding data members It is the process of eliminating unimportant
of a class to the member function of that details of a class. In this process only important
class properties are highlighted.
2 Data encapsulation depends upon object Data abstraction is independent upon object data
data type. type.
3 It is used in software implementation It is used in software design phase.
phase.
4 Data encapsulation can be achieved by Data abstraction is represented by using abstract
inheritance. classes.
Introduction to C++
 The language C++ (pronounced as see plus plus) was developed by Bjarne Strousstrup in
1979 at Bell Labs.
 It is popularly known as a object oriented programming language. This language is
compiled.
 C++ began as an enhancement to C, first by adding classes, virtual functions, inheritance
and many other features.
5
Difference between C and C++
S.No. C language C++ language
C++ is an object oriented programming
1 C is a procedure oriented language
language.
C makes use of top down approach of C++ makes use of bottom up approach of
2
problem solving problem solving.
The input and output is done using scanf The input and output is done using cin and
3
and printf statements cout statements.
The I/O operations are supported by The I/O operations are supported by
4
stdio.h header file. iostream.h header file.
C does not support inheritance,
C++ supports inheritance, polymorphism,
5 polymorphism, class and object
class and object concepts.
concepts.
The data type specifier or format
The format specifier is not required in cin
6 specifier (%d, %f, %c) is required in
and cout
printf and scanf functions.

Advantages of OOP
Following are some advantages of object oriented programming –
1. Using inheritance the redundant code can be eliminated and the existing classes can be used.
2. The standard working modules can be created using object oriented programming. These
modules can then communicate to each other to accomplish certain task.
3. Due to data hiding properly, important data can be kept away from unauthorized access.
4. It is possible to create multiple objects for a given class.
5. For upgrading the system from small scale to large scale is possible due to object oriented
feature.
6. Due to data centered nature of object oriented programming most of the details of the
application model can be captured.
7. Message passing technique in object oriented programming allows the objects to
communicate to the external systems.
8. Partitioning the code for simplicity, understanding and debugging is possible due to object
oriented and modular approach.

6
Disadvantages of OOP
Following are some drawbacks of OOP –
1. The object oriented programming is complex to implement, because every entity in it is an
object. We can access the methods and attributes of particular class using the object of that
class.
2. If some of the members are declared as private then those members are not accessible by the
object of another class. In such case you have to make use of inheritance property.
3. In Object oriented programming, everything must be arranged in the forms of classes and
modules. For the lower level applications it is not desirable feature.
Applications of OOP
Various applications in which object oriented programming is preferred are –
 Business logic applications
 Real time systems.
 Knowledge based and expert systems
 Web based applications
 Simulation modeling
 Object oriented databases
 Applications in distributed environment
 CAD / CAM systems
 Office automation system
 Games programming
C++ Program Elements
Every C++ Program contains the logical units called tokens. These token are basically collection of
characters that belongs to some category. For instance – the tokens in C++ can be identifiers,
keywords, operators, literals and so on.
Comments
 Comments are those statements in the program which are non executable in nature. They
provide simply the information about the programming statements.
 There are two ways by which we can give the comments in C++. The first way is similar to
comments in C. The start of the comment is /* and end of the comment is */. This comment
statement is a multiline comment statement that means you can comment many lines
together using /* and */
 Another way is / / at the start of the line which is to be commented. This is a single line
comment statement. The comment statements are useful in documenting the program.

7
Keywords
Keywords are special reserved words associated with some meaning. The keywords are –
asm enum private throw
auto explicit protected true
bool export public try
break extern register typedef
case false reinterpret_cast typeid
catch float return typename
char for short union
class friend signed unsigned
const goto sizeof using
const_cast if static virtual
continue inline static_cast void
default int struct volatile
delete long switch wchar_t
do mutable trmplate while
double namespace this
dynamic_cast new
else operator

Identifiers
 The identifier is a sequence of one of more letters or alphanumeric characters.
 The valid identifier should follow following rules.
 The identifier should not start with digits.
 No special character is allowed in identifier except underscore.
 There should not be any blank space with the identifier name.
 The identifier name should not be keyword.
 The identifier name should be meaningful.
For example –
Valid Identifiers Invalid Identifiers
index1 12A
total_marks total marks
count_1 count#1
value char

Literals
Literals are the constant values. Constants are used to define the fixed values in C++.
For example
100 Decimal number
78.66 Real number with decimal point
“Hello” String constant
‘T’ Character constant
8
Escape Sequence
There are non printing special characters which are called escape sequences.
Following table shows the list of escape sequences along with their purpose
Character Constant Meaning

\\ backslash
\b backspace
\” Double quotes
\n Newline
\t tab
\’ Single quote
\0 Null Character
Operators
 Expressions are some mathematical logical units which are mainly used to perform some
arithmetic calculations. Generally the expressions are used along with the operators.
 For example: a+b is a simple expression in which the plus operator is used to perform
addition of two numbers. And this addition if you want to store in the variable c then in C++
language we will write it as c=a+b.
 Note that the assignment of the value is from right to left. Irrespective of the data types of a
and b the data type of c variable will be considered for storing the final result.
Hierarchy of Operations
Priority Operators
1 *, /, %
2 +,-
3 =
 In the hierarchy of operations, based on the priority of the operators the operations are
performed. And scanning of the expression will be from left to right.
For example:
20-2+3*5/3
Step 1:
Scanning from left to right we come across - ,+ and * operators the highest priority is to * so
perform 3*5 first.
Step 2:
In the expression 20-2+15/3 now the division will take place.

9
Step 3:
In the expression 20-2+5 the subtraction will be performed, since + and – have the same
priority the operator coming first from left side will be considered.
Step 4:
In the expression 18+5; the evaluation will result to 23.
To learn the expression it is very much necessary to get introduced with the operators.
Type Operator Meaning For example
+
Arithmetic Addition or unary plus c = a+b
- Subtraction or unary minus d = -a , c = a-b
* Multiplication c=a*b
/ Division c=a/b
% Mod a%b
Relational < Less than a<4
> Greater than a>4
<= Less than equal to a<=4
>= Greater than equal to a>=4
== Equal to a==4
!= Not equal to a!=4
Logical && And 0 && 1
|| Or 0||1
Assignment = Is assigned to a=5
Increment ++ Increment by one ++i or i++
Decrement -- Decrement by one - - x or x - -
Conditional Operator
The conditional operator is “ ? “. The syntax of using conditional operator is
condition?expression1:expression2
for example
a>b?true:false
This means if a is greater than b, if yes then the value will be true otherwise it will be false.
C++ Program
#include<iostream.h>
void main( )
{
int a,b,c;
a=3;
b=7;
10
cout<<”\n The value of a =”<<a;
cout<<”\n The value of b=”<<b;
cout<<”\n The addition of a+b=”<<a+b;
cout<<”\n The subtraction of a-b=”<<a-b;
cout<<”\n The multiplication of a*b=”<<a*b;
cout<<”\n Use of conditional operator…”;
c=(a>b) ? a : b;
cout<<c;
}
Output
The value of a = 3
The value of a = 7
The addition of a+b = 10
The subtraction of a-b = 4
The multiplication of a*b = 21
Use of conditional operator…7
enum
To create user defined type names the keyword enum is used. The syntax of using enum is
enum name{list of names} variables;
for example
#include<iostream.h>
void main( )
{
enum mylist{small,middle=5,large}a,b;
a=middle;
b=large;
cout<<”a=”<<a<<”b=”<<b;
}
Output
a= 5 b= 6
Program Structure
There are four sections in the structure of C++ program –
Include file section
Class declaration section
Function definition section
Main function definition
Structure of C++ program
C++ Program
// This is the first C++ program
#include<iostream.h>
void main()
{
cout<<”Hello world”;
}
Output
11
Hello world

Input and Output


 In C++ the input operation is called extraction because data is extracted from keyboard and
the operator >> is called extractor.
 The C++ statement input operation will be –
cin >> a
 This input statement on execution will wait for the user to type in a number using keyboard,
the value entered by user will then be saved in a variable.
 The C++ uses an output operation called insertion because data is inserted or sent from the
variable. The operator << is called insertion operator.
 The C++ statement for output operation will be –
cout << a;
 The data contained in variable a will be displayed on the screen.
Data Types
The data types are specified by a standard keyword. The data types are used to define the type of
data for particular variable. Various data types that are used in C++ is enlisted in the following table
Type Size Range
char 1 byte -127 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -127 to 127
int 4 bytes -2147483648 to 2147483647
unsigned int 4 bytes 0 to 4294967295
signed int 4 bytes -2147483648 to 2147483647
short int 2 bytes - 32768 to 32767
unsigned short int 2 bytes 0 to 65,535
signed short int 2 bytes - 32768 to 32767
long int 4 bytes -2,147,483,648 to 2,147,483,647
signed long int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295
float 4 bytes + / - 3.4e + / - 38
double 8 bytes + / - 1.7e + / - 308
long double 8 bytes + / - 1.7e + /- 308

12
Type Conversion
Definition: The type conversion is a process in which variable in one data type can be converted to
another data type.
 Some data types can be automatically converted by the compiler. This automatic conversion
is called as an implicit conversion.
For example:
#include<iostream.h>
void main( )
{
int x;
float y=99.99;
x=y; // here the value becomes 99 and .99 will be truncated.
}
 Similarly, we can make use of type cast to explicitly convert one type to another basic type.
This type of conversion is called explicit conversion.
 In C++ the type casting is done in two ways –
 C style type casting
 C++ style type casting
 The syntax for C style type casting is as follows –
(datatype) expression
For example
(double)2/3;
 The syntax for C++ style type casting is as follows –
Datatype(expression)
C++ program
//Program for demonstrating the type conversion
#include<iostream.h>
void fun1( )
{
int a;
double b,m ans;
a=2;b=11.10;
ans=(double)a*b;
cout<<ans<<endl;
}
void fun2( )
{
int a;
double b,ans;
a=2;b=11.10;
ans=double(a)*b;
13
cout<<ans<<endl;
}
void main( )
{
cout<<”The C style type casting”<<endl;
fun1();
cout<<”The C++ style type casting”<<endl;
fun2();
}
Output
The C style type casting
22.2
The C++ style casting
22.2

Control Structures
Let us list out some control statements –
1. If statement
2. While statement
3. Do while statement
4. Switch- Case statement
If statement:
The if statement is of two types
i) Simple if statement: The if statement in which the only one statement is followed by that if
statement.
Syntax
if(apply some condition)
Execute this statement if condition is true
For example:
if(a>b)
cout<<”\n a is Biiiig!”;
ii) Compound if statement:
If there are more than one statements those have to be executed when the if condition is true. All
these executable statements are placed in curly brackets.
Syntax
if(condition is true)
{
Execute this statement
And this statement

14
And this statement
And this statement
Probably many more
}
if else if statement
Syntax
if (condition is true)
execute this statement
else if(is this another condition is true?)
execute this statement
else if(is this another condition is true?)
execute this statement
else if(is this another condition is true?)
execute this statement
else
this is the final chance of your condition
C++ Program
/*******************************************************************************
Program for fixing the bonus of employee using nested if else if statement
*******************************************************************************/
#include<iostream.h>
void main()
{
long int basic;
float bonus,gross;
cout<<”\n Enter The basic Salary”;
cin>>basic;
if(basic<10000)
{
bonus=0.75*basic;
gross=basic+bonus;
cout<<”\n Your Salary is = “<<gross;
}
else if(basic>10000&&basic<=20000)
{
bonus=0.50*basic;
gross=basic+bonus;
cout<<”\n Your salary is = “<<gross;
}
else if(basic>20000&&basic<=50000)
{
bonus=0.25*basic;
gross=basic+bonus;
cout<<”\n Your salary is = “<<gross;
}
else
{
bonus=0.0;

15
gross=basic+bonus;
cout<<”\n no Bonus and yoursalary is =”<<gross;
}
}
Output
Enter the basic salary 55000
no Bonus and Your Salary is = 55000
Switch case statement
You can compare the switch statement with the menu-card in the hotel. You select the menu and
that only will be served to you.
In Switch statement directly the statement is executed which is matching with the codition.
C++ Program
/*******************************************************************************
Program for using switch-case statement
*******************************************************************************/
#include<iostream.h>
void main()
{
int choice;
cout<<”Enter your choice “;
cin>>choice;
switch(choice)
{
case 1:
cout<<”\n Your choice is number 1”;
break;
case 2:
cout<<”\n Your choice is number 2”;
break;
default:
cout<<”\n Choice is other than number 1,2,3”;
}
}
Output
Enter your choice 5
Choice is other than number 1,2 and 3

Do while statement:
 The other form of the control statement is do… while statement.
 In the do… while the statements inside the do … while body has to be executed at least
once.
 The way to write the do… while statement is as follows –
do
{
execute this statement;
execute this statement also;

16
execute this statement also;
that’s all;
} while(some condition);

C++ Program
/*******************************************************************************
Program for using do while statement
*******************************************************************************/
#include<iostream.h>
void main()
{
int count=1;
do
{
cout<<”\n I am on the first line of do-wile”;
count++;
}while(count<=5);
}
while statement
 The other form of the control statement is while statement.
 The while statement is exactly similar to the do… while statement.
 In the while statement the condition is first of checked, if it is true then the statements in the
while body are executed.

while(condition is to be checked)
{
execute this statement;
execute this statement also;
execute this statement also;
that’s all;
}

C++ Program
/*******************************************************************************
Program for using while statement
*******************************************************************************/
#include<iostream.h>
void main()
{
int count=1;
while(count<=5)
{
cout<<”\n I am on the first line of do-wile”;
count++;
}
}

For loop :
17
 It is an very interesting topic of the control structures and that is looping.
 The for is a keyword for applying loops in the program.
 The for loop can be categorized in to two
 Simple for loop
 Compound for loop

Simple for loop


for(statement1;statement2;statement3)
execute this statement;
Compound for loop
for(statement1;statement2;statement3)
{
execute this statement;
execute this statement also;
execute this statement also;
that’s all;
}
statement1 – It is always for initializing the conditional variables.
statement2 – It represents the terminating condition of the for loop.
statement3 – It is for representing the stepping for the next condition.

C++ Program
/*******************************************************************************
Program for using for loop
*******************************************************************************/
#include<iostream.h>
void main()
{
int count;
for(count=1;count<=5;count=count+1)
{
cout<<”\n Testing the for loop, Tested OK!”;
cout<<”\n printing the statement for”<<count<<”time”;
}
}
Output
Testing the for loop, Tested OK!
printing the statement for 1 time
Testing the for loop, Tested OK!
printing the statement for 2 time
Testing the for loop, Tested OK!
printing the statement for 3 time

18
Testing the for loop, Tested OK!
printing the statement for 1 time
Testing the for loop, Tested OK!
printing the statement for 1 time

Functions
 Writing functions in any program is always an ideal practice. Because functions bring out
modularity in our programs.
 We can find bugs in the program very efficiently and other working module cannot be
disturbed.
Programmer handles the C++ functions using following methods –
1. Definition of function
2. Call to the function.
In C++ normally we write all the function definitions just before the void main() function.

Types of the function


1. Passing nothing and returning nothing.
2. Passing the parameters and returning nothing.
3. Passing parameters and returning something.
Let us understand each of the type with some example.
Type 1. Passing Nothing and Returning Nothing
C++ Program
#include<iostream.h>
void sum()
{
int a,b,c;
cout<<”\n Enter the two numbers”;
cin>>a;
cin>>b;
c=a+b;
cout<<”\n The addition of two numbers are “<<c;
}
void main()
{
sum();
}
Output

19
Enter the two numbers: 2 3
The Addition of two numbers are 5
Here that no parameter is passed in the function. Similarly no return statement is written in the
function sum.
Hence we have given the data type for the function sum as void. The void means returning nothing
or NULL. It is always good to give the data type for the function main as void, because it is return
nothing.

Type 2. Passing the Parameter and Returning Nothing.


C++ Program
#include<iostream.h>
void sum(int x,int y)
{
int c;
c=x+y;
cout<<”\n The addition of two numbers are “<<c;
}
void main()
{
int a,b;
cout<<”\n Enter the two numbers”;
cin>>a;
cin>>b;
sum(a,b);
}
Output
Enter the two numbers: 5 7
The Addition of two numbers are 12
There are actually two ways of parameter passing.
1. Call by Value.
The above example which we have discussed is of parameter passing by call by value. This
is called by value because the values are passed.
2. Call by Reference
In call by reference the parameters are taken by reference. Pointer variables are passed as
parameters.
e.g.
C++ Program
#include<iostream.h>
void sum(int *x,int *y)
{
int c;
20
c=*x+*y;
cout<<”\n The addition of two numbers are “<<c;
}
void main()
{
int a,b;
void sum(int *,int *);
cout<<”\n Enter the two numbers”;
cin>>a;
cin>>b;
sum(&a,&b);
}
Output
Enter the two numbers: 5 6
The Addition of two numbers are 11
Type 3. Passing the Parameters and Returning from the Function
In this method the parameters are passed to the function. And function also returns something.
Depending upon that something the data type of the function gets decided.
For returning any value the keyword return is used.
C++ Program
#include<iostream.h>
int sum(int a,int b)
{
int c=a+b;
return c;
}
void main()
{
int a,b,c;
int sum(int,int);
cout<<”\n Enter the two numbers”;
cin>>a;
cin>>b;
c=sum(a,b);
cout<<”\n The addition of two numbers are “<<c;
}
Output
Enter the two numbers: 4 5
The Addition of two numbers are 9

21