Professional Documents
Culture Documents
Introduction
C programming language is a Procedure Oriented Programming (POP) wherein the
main emphasis is on data and functions. One serious drawback in this approach is that it does not
model real world problems very well.. The main emphasis to introduce a new programming
paradigm Object Oriented Programming (OOP) and particularly this chapter describes about
what are the different its different features and what are the advantages of this new paradigm.
Programming Paradigms
Programming style is defined as a way of organizing the ideas on the basis of some
conceptual model of programming and using an appropriate language to write efficient
programs.
The two main programming styles are:
Procedure-Oriented
Object Oriented.
No single programming style is best suited for all kinds of applications. For example,
Procedure-oriented programming would be best suited for the design of computation-intensive
problems and Object oriented programming style is best suited for a wide range of application. It
also serves as the architectural frame work in which other paradigms are employed.
Main Program
Function - 1
Function - 2
Function 4
Function - 6
Function - 3
Function - 5
Function - 7
Function - 8
Functions that operate on the data of an object are tied together in the data structure.
Object B
Data
Data
Function
s
communication
Function
s
Data C
Object
Function
s
Definition of OOP:
An object is a combination or collection of data and code designed to emulate a physical
or abstract entity. Each object has its own identity to distinguishable from other objects, a set of
properties and behavior.
Object oriented programming gives importance to relationships between objects rather
than implementation details. Hiding the implementation details within an object results in the
user being more concerned with an objects relationship to the rest of the system, than the
implementation of the objects behavior.
7. Message passing
1. Objects
In general, the object can be represented as a real thing entity that has an identity and
possessed some properties and behavior.
For example, an electric bulb is made by some company (identity) and it as some shape and
wattage (properties) and gives light (behavior).
Technically, objects are the basic run-time entities in an object-oriented system. They
may represent a person, a place, a bank account, a table of data or any item that the program has
to handle. The problem is analyzed in terms objects and the nature of communication between
them. The objects should be chosen in such a way they match closely with the real world objects.
5
When the program is executed, the objects interact by sending messages to one another.
For example, if customer and account are two objects in a program, then the customer object
may send a message to the account object requesting for the bank balance.
Every object will have data structures called attributes and behavior or operations that
manipulate the data. The different notations of an object uniting both the data and operations are
shown in figure.
Object : STUDENT
Total
DATA: Name
Date of Birth
Marks
STUDENT
Average
FUNCTIONS:
Total
Average
Display
Display
2. Classes
We just discussed that objects contain both data and operations to manipulate the data.
Both the data and operations of an object put together with the help of a class and made them as
a user defined data type. In other sense, the objects are the variables of the class.
Once the class has been defined, we can create any number of objects belonging to that class. So,
a class is a collection of objects of similar type.
Example: In the class Person all the objects have similar data like Name, age, Sex and
operations like Speak, Listen, and walk. So boy and girl objects are grouped in to the Person
class.
Class Person
Data: Name, Age, Sex
Operations: Speak ( ), Listen ( ), Walk ( )
Person boy, girl;
4. Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects
of another class. It supports the concept of hierarchical classification. It allows the declaration
and implementation of one class to be based on an existing class.
For example, If the class Child inherits the all the features of class Parent, then the class Parent
referred as base class(super class) and the class child referred as derived class(sub class).
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by deriving
a new class from the existing one. The new class will have the combined features of both the
classes.
Parent features
Figure : Inheritance
7
5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
the ability to take more than one form. An operation may exhibit different behaviors in different
instance. The behavior depends upon the types of data used in the operation.
For example, the operation addition can add two numbers but, the same operation when applied
on two strings, it concatenates.
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading. Similarly, a single function name can also behave differently
depending on the different number and different types of arguments and depending on the
context.
For example, the function Draw ( ) can be used to draw a circle, or a line or triangle depending
on where it is used. The process of using a single function to perform different tasks is known as
function overloading.
Shape
Draw ( )
Circle Object
Box Object
Triangle Object
Draw (circle)
Draw (box)
Draw (triangle)
Figure: Polymorphism
6. Dynamic binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding (also known as late binding) means that the code associated with a
given procedure call is not known until the time of the call at run-time. It is associated with
polymorphism and inheritance.
7. Message passing
8
Object
message
information
Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object-orientation
contributes to the solution of many problems associated with the development and quality of
software products. The advantages are:
Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
We can build programs from the standard working modules that communicate with one
another.
The principle of data hiding helps the programmer to build secure the programs.
Data encapsulation
Operator overloading
Languages that support programming with objects are said to be object-based programming
languages. They do not support inheritance and dynamic binding. Ada is a typical object-based
programming language.
2. Object-oriented programming: It is incorporates all of object-based programming features
along with two additional features, namely inheritance and dynamic binding.
Object Oriented features =object-based features + inheritance + dynamic binding
Languages that support these features include C++, Smalltalk, Object Pascal and java.
Features of OOP
10
Functions that operate on the data of an object are tied together in the data structure.
Applications of OOP
11
Applications of OOP are beginning to gain importance in many areas. The most popular
application of OOP is in the area of user interface design such as windows. The other areas
include the following:
i)
Real-time systems
ii)
iii)
iv)
v)
vi)
vii)
viii)
CIM/CAM/CAD systems
The richness of OOP environment has enabled the software industry to improve not only the
quality of software systems but also its productivity.
//header file
//main function
{
cout<<Welcome to C++ language for students;
//C++ statement
return 0;
} //end of program
Output:
Welcome to C++ language for students
This program demonstrates several C++ features.
Comments:
C++ introduces a new comment symbol //(double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the program
and whatever follows till the end of the line is ignored. There is no closing symbol.
Ex.
//this is an example program
// for learners
The C comments /*
.. */ are also valid and are more suitable for multiline comments.
{
----------;
-----------;
-----------;
return 0; //return zero statement
}
right to the object on its left. This corresponds to familiar printf() operation in C.
Screen
C++
<<
cout
Object
Insertion Operator
Variable
Input Operator:
The syntax of cin statement:
cin>>variable_name; // cin is used for reads the value from keyboard
is an input statement and causes the program to wait for the user to type in a number. This
number keyed in is placed in the particular variable_name. The identifier cin (pronounced
Cin) is also a predefined object in C++ that corresponds to the standard input stream (i.e., key
board in this case).
Object
Extraction operator
cin
>>
Variable
45.5
Keyboard
Figure: Input using extraction operator
The operator >> is known as extraction or get from operator. It extracts (or takes) the value
from the keyboard and assigns it to the variable on its right. This corresponds to the familiar
15
scanf() operation in C.
#include<iostream>
Using namespace std;
int main( )
{
int i;
float f;
char ch;
char name[50];
cout<<Enter the integer, float and character:;
cin>>i>>f>>ch;
return 0;
}
Output:
Enter the integer, float and character: 3
6.5
f = 6.5
ch = A
name = RAJU&RAMESH
Declaration of Variables:
All the variables must be declared before they are used in the program. Provided unlike in
C, in C++ you can declare the variables whenever there is a need for you any where in the
program even between the statements also.
Program 3: Write a program to find sum and average of two numbers.
# include < iostream>
int main()
{
float num1, num2;
//declaration of variables
//declaration
sum=num1+num2;
cout<<Sum is:<<sum;
float average;
//declaration
average=sum/2;
cout<<Average is:<<average;
return 0;
17
}
Output:
Enter two numbers: 3.3
5.3
Include files
Class declaration
Member functions definitions
Main function program
Structure of C++ program
It is a common practice to organize a program into three files. The class declarations are placed
in a header file and the definitions of member functions go into another file. This approach
enables the programmer to separate the abstract specification of the interface (class definition)
from the implementation details (member functions definition). Finally, the main program that
uses the class is placed in a third file which includes the previous two files as well as any other
files required.
Some of them(sections) are optional.
1) Include Files:
The class declaration must be enclosed with curly braces ({ }) and terminated by a semi
colon(;).
Syntax:
class <class name>
{
Variables declaration; // called as data members (or) member variables
Function declaration/definition; // called as member functions
};
// End of class
The class function definition can be done outside or inside the class declaration.
When the function is large then define outside the class. In this case prototype or
declaration of a function must be declared inside the class.
4) main( ) function:
Every C and C++ program execution starts from main( ) function, hence it is
compulsory.
19
time
return 0;
}
Output:
Enter radius: 3
Area = 28.26
Reference Variables
C++ introduces a new kind of variable known as the reference variable. Reference
variable behaves similar to both, a value variable and a pointer variable i.e., a reference variable
provides an alias (alternative name) for a previously defined variable. Thus the reference variable
enjoys the simplicity of value variable and power of the pointer variable.
The general format of declaring a reference variable is:
data-type & reference-name = variable-name;
Examples:
float total=100;
float & sum = total;
total is a float type variable that has already been declared. sum is the alternative name
20
declared to represent the variable total. Both the variable refer to the same data object in the
memory.
cout<<total;
cout<<sum; // Both statements prints the value 100.
The reference variable must be initialized at the time of declaration. Initialization of reference
variable after its declaration causes compilation error. Hence, reference variables allow creating
alias of existing variables.
The following examples uses reference variable
1. int n[10];
int & x=n[10];
2. int x;
int *p = &x ;
int &m = *p;
3. int & n = 50;
A major application of reference variables is in passing arguments to functions.
Mainly they are three types of passing arguments to functions.
1. call by value
2. call by address
3. call by reference parameters
Already we have seen first two types in C
3.call by reference:
Program 5: Illustrating the use of reference variable in parameter passing
#include<iostream>
using namespace std;
void fun(int &x)
//uses reference
{
x=x+10;
}
int main()
{
int m=100;
21
//function call
Output:
Before call of function 100
After call of function 110
In the above program the parameter x in function fun becomes an alias for the variable
m passed from main(). This type of function calls are known as call-by-reference.
Since both x and m are aliases , when the function increments x, m is also incremented. In
traditional C we can accomplish this operation using pointers and dereferencing techniques.
The call-by-reference mechanism is useful in object-oriented programming because it permit
manipulation of objects by reference, and eliminates the copying of object parameters back and
forth. The reference variables not only use for built-in types, it can also use for user-defined
variables.
Operators in C++
All C operators are valid in C++ also. C++ introduces some of the following new
operators along with << and >> as we already used.
::
::*
pointer-to-member declarator
->
pointer-to-member operator
.*
pointer-to-member operator
endl
setw
22
In addition, C++ also allows us to provide new definitions to some of the build-in operators. That
is, we can give several meanings to an operator, depending upon the types of arguments used.
This process is known as operator overloading.
:: global variable-name
The global variable-name to be accessed must be preceded by the scope resolution
operator. It directs the compiler to access a global variable, instead of one defined as a local
variable. Thus, the scope resolution operator permits a program to reference an identifier in the
global scope that has been hidden by another identifier with the same name in the local scope.
Program 6: Global variable access through : :
#include < iostream >
using namespace std;
int num=100;
//global variable
int main()
{
int num=10;
//local variable
cout<<Local = <<num;
cout<<Global=<<::num;
return 0;
}
Output:
Local=10
Global=100
23
In the above program the variable num is declared both locally and globally. The notation:: num
refers to global variable.
::*
2.
.*
3.
-->*
These operators are simply the improved versions of the functions malloc(), calloc() and free() in
C which are used for the same purpose.
An object can be created by using new operator and destroyed by using delete as and when
24
required. A data object created inside a block with new, will remain in existence until it is
explicitly destroyed by using delete. Thus, the lifetime of an object is directly under our
control.
new operator:
1) The new operator can be used to create objects of any type.
The general format is:
Pointer-varaible = new data-type;
Here, the pointer-variable is a pointer of type data-type. The new operator allocates sufficient
memory to hold a data object of type data-type (a valid data-type) and returns the address of the
object. The pointer-variable holds the address of the memory space allocated.
Example:
int *p;
p=new int;
*p=25;
p=new int(25);
3) The new operator can also be used to create memory for any data type including userdefined data type such as arrays, structures and objects etc.
The general format for creating dynamic memory for single dimensional array is
Pointer-variable = new data-type [size];
where the size is an integer variable.
Example:
int *arr;
25
delete operator:
When a data object is no longer required, it is destroyed to release the memory space for
reuse.
The general format is:
delete pointer-variable;
The pointer-variable is the pointer that points to a data object created with new.
Example:
delete p;
Example
delete [ ] arr ; // delete data object of an array
Manipulators
Manipulators are operators that are used to format the data display. The most commonly
used manipulators are endl and setw.
The endl when used in output statement, causes a linefeed to be inserted. It has the same effect
of using the new line character \n.
Example
cout<<Hai<<endl;
cout<<Hello<<endl;
cout<<Bye<<endl;
The above example produces three lines of output for each statement.
Output:
Hai
26
Hello
Bye
The setw manipulator is used to display the output in the specified width. To use this
manipulator we has to include iomanip.h header file in the program.
The statement
cout<<setw(5)<<sum<<endl;
produces the value of sum in the width of 5 characters with right-justification including the
character output.
1
// for setw
950
Allowance
Total
95
1045
(datatype_name) expression
// C notation
datatypename ( expression)
//C++ notation
Example:
average=sum/(float)n;
// C notation
average=sum/float(n);
//C++ notation
Introduction of Classes
The most important feature of C++ is the class. Its significance is highlighted by the
fact. A class is an extension of the idea of structure used in C. It is a new way of creating and
implementing a user-defined type (data). We shall discuss the concept of class by first reviewing
the traditional structures found in C and then the ways in which classes can be designed,
implemented and applied.
The functions defined within a structure have a special relationship with the structures
elements presents within the structure.
There is another entity in C++ called class that too can hold data and functions.
Most of the C++ programs use classes to hold both data and functions.
In structures we have to give type for alias names but in case classes no need.
Structure should call its own data with a help of dot operator.
Specifying a Class:
1. Class Definition:
A class is a way to bind the data and its associated function together. It allows the data to
28
be hidden, if necessary from external user. When defining a class, we are creating a new abstract
data type that can be treated like any other built is data type.
A Class can be specified in two parts:1. Class declaration.
2. Class function definitions.
The class declaration describes the type and scope of its member.
The class function definitions describe how the class functions are implemented.
class
<class-name>
29
Note: The binding of data and functions together into a single class type variable is referred to as
30
encapsulation.
Lets have an example about class:A typical class declaration:-
class item
{
private:
int number;
// variable declaration
float cost;
// variable declaration
public:
void getdata (int a, float b); // functions declaration
void putdata (void);
};
// using prototype
(or)
class item
{
int number;
// variable declaration
float cost;
// private by default
public:
void getdata (int a, float b); // functions declaration
void putdata (void);
};
// using prototype
2. Creating Objects:
Once a class has been declared, we can create variable of that type by class name. The
class variables of class are called as objects.
The declaration of an object is similar to that of a variable of any basic type. And the
necessary memory space is allocated to an object at this stage.
31
Syntax:
classname
variablename;
x;
Example:
class item
{
int number;
// variable declaration
float cost;
// private by default
public:
32
// using prototype
};
Accessing members:
item x;
// x is object
33
{
Function-body
}
Note:- The scope of the function is restricted to the class name specified in the header
line.
A member function can call another member function directly, without dot operator.
34
35
// declaration
// access specifier
void
void
{
cout<<number:<<number<<endl;
cout<<cost:<<number<<\n;
}
};
{
number = a;
cost = b;
}
int main ( ) //main function with return int
{
item x;
//object created
x.putdata( ) ;
item y;
y.putdata( );
return 0;
}
// end of main
Output:
object x
number:100
cost:299.5
object y
number:200
cost:175.5
int m , n;
public:
void input( );
void display( );
int largest( );
};
int set :: largest( )
{
if( m >= n )
return (m);
else
return (n);
}
void set :: input( )
{
cout<< Input values of m and n<<endl;
cin>> m >> n;
}
void set :: display( )
{
cout<< largest value=<<largest( ); // calling member function
}
int main( )
{
set A;
// A is object
A.input( );
A.display( );
return 0;
}
Output:
38
25 18
Largest value = 25
We can place the member functions in private section. A private member functions can
only be called by another public member functions of its class. Even an object cannot invoke a
private function using the dot-operator.
class
sample
{
private:
void fun1 ( );
public:
void fun2 ( );
void fun3 ( );
};
If S is an object of sample, then
S.fun1 ( ); //wont work objects cannot access private members is illegal, However, the
function fun1( ) can be called by the fun2( ) or fun3( ).
That is,
void sample :: fun2( )
{
fun1( ); // private member function calling
}
Note: A private member functions can be called by using its name in any public member
functions of the same class. No need of any object for this.
39
40