You are on page 1of 40

UNIT I

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.

Procedure Oriented Programming (POP)


Conventional programming, using high level languages such as COBOL, FORTRAN and
C are commonly known as procedureoriented programming (POP). In this style the problem
is viewed as a sequence of things to be done such as reading, calculating and printing. A number
of functions are written to accomplish these tasks. The primary focus is on functions.

Main Program

Function - 1

Function - 2

Function 4

Function - 6

Function - 3

Function - 5

Function - 7

Function - 8

Figure : procedure oriented programming style.


Procedure oriented programming basically consists of writing a list of instructions in the
form of functions. While concentrating function, very little attention is given to the data that are
being used by various functions.
When a program contains many functions, many important data items are placed as
global so that they may be accessed by all the functions. Each function may have its own local
data. The global data are more at risk to an involuntary change by a function. Not only that it is
also very difficult to trace out what data is used by which function. While revising any of the
data structure, we need to revise the functions that access the data.
Another serious drawback with the procedural approach is that it does not model real world
problems very well.
Some characteristics exhibited by POP:

Emphasis is on doing things(algorithms).

Large programs are divided into smaller programs known as functions.

Most of the functions share global data.

Data move openly around the system from function to function.

Functions transform data from one form to another.


3

Employs top-down approach in program design.

Object Oriented Programming Paradigm (OOP)


Object-Oriented Programming paradigm is the most recent concept among programming
paradigms. The major motivating factor in the invention of object-oriented approach is to remove
some of the flaws encountered in the procedural approach. OOP treats data as a critical element
in the program development and does not allow it to flow freely around the system. It ties data
more closely to the function that operate on it, and protects it from accidental modification from
outside functions. OOP allows decomposition of a problem into a number of entities called
objects and then builds data and function around these objects. The organization of data and
function in object-oriented paradigm is shown in fig. The data can be accessed only by the
functions associated with that object. However the functions of one object can access the
functions of other objects.
Some of the features of OOP:
Emphasis is on data rather than procedure.

Programs are divided into objects.

Functions that operate on the data of an object are tied together in the data structure.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions.

New data and functions can be easily added whenever necessary.

Follows bottom-up approach in program design.


Object A

Object B

Data

Data

Function
s

communication

Function
s

Data C
Object

Function
s

Figure:Organization of Data and Functions in OOP


4

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.

Basic Concepts of Object-Oriented Programming (OOP)


The following are some of the features used extensively in object-oriented programming.
They are:
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding

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

Figure : two ways of representing objects

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;

//objects of class Person

3. Data Abstraction and Encapsulation


The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of class. The data is not accessible
to the outside world, and only those operation or functions which are wrapped in the class can
access it. These functions provide the interface between the objects data and the program. This
insulation of the data from direct access by the program is called data hiding or information
hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a
list of abstract data such as Name, age, Sex and operations to operate on these attributes. The
class encapsulates all the essential properties of the objects that are to be created. The attributes
are known as data members and operations are know an member functions or methods.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Type(ADT).

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

Parent feature &


Childs features

Base or Super class - Parent

Derived or sub class - Child

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

In conventional programming languages, a function is invoked on a piece of data


(function-driven communication), where as in OO languages, a message is sent to an object
(message driven communication).
In OO languages, the programming involves the following steps.
1. Creating classes that define objects and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another, The concept of message passing makes it easier to
talk about building systems that directly model or simulate their real-world counterparts.
A message for an object is a request for execution of a function. It invokes a function in
the receiving object that generates the desired result. It involves specifying the name of the
object, the name of the function (message) and the information to be sent.

Boy. Speaks (English);

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.

This leads to saving of development time and higher productivity.


9

The principle of data hiding helps the programmer to build secure the programs.

It is easy to partition the work in a project based on objects.

Software complexity can be easily managed.

While it is possible to incorporate all these features in an object-oriented system, their


importance depends on the type of the project and the preference of the programmer.
Developing a software that is easy to use makes it hard to build. It is hoped that the
object-oriented programming tools would help manage this problem.

Object Oriented Languages


The languages should support several of the OOP concepts to claim that they are object
oriented languages. Depending upon the features they support, they can be classified into the
following two categories:
1. Object-based programming languages.
2. Object-oriented programming languages.
1. Object-based programming: It is the style of programming that primarily supports
encapsulation and object identity. Major features that are required for object based programming
are.

Data encapsulation

Data hiding and access mechanisms

Automatic initialization and clear-up of objects

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

Some of the features of OOP:

Emphasis is on data rather than procedure.

Programs are divided into objects.

Functions that operate on the data of an object are tied together in the data structure.

Data is hidden and cannot be accessed by external functions.

Objects may communicate with each other through functions.

New data and functions can be easily added whenever necessary.

Follows bottom-up approach in program design.

How OOP differ from POP


Program and data are two basic elements of any computation. Among these, data plays an
important role and it can exist without a program, but a program has no relevance without data.
The high level languages stress on the algorithms used to solve a problem. When the
data defined as global, then data is accessible to all functions of a program without any
restriction. This method has reduced data security and integrity, since the entire data is available
to all the functions and any function can change any data.
Unlike the traditional methodology (POP), OOP emphasized on the data rather than the
algorithm. In OOPs data is encapsulated with the associated functions and this compartment is
called as object. In the OO approach, the problem is divided into objects, whereas in POP the
problem is divided into functions.
OO languages allow localization of data and code and restrict other objects from referring
to its local region. OOP is centered around the concepts of objects, encapsulation, inheritance,
polymorphism, message based communication, etc.
During the execution of a program, the objects interact with each other by sending
messages and receiving responses. For instance, in a program to perform withdrawals from an
account, a customer object can send a withdrawal message to a bank account object. An object
communicating with other objects need not be aware of the internal working of the objects with
which it interacts. The objects internal structure is totally hidden from the user and this property
is called data/information hiding or data encapsulation.

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)

Simulation and modeling

iii)

Object-oriented data bases

iv)

Hypertext and hypermedia

v)

AI and expert systems

vi)

Neural networks and parallel programming

vii)

Decision support and office automation systems

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.

Brief History of C++


C++ is a object-oriented programming language. It was developed by Bjarne Stroustrup
at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980s. It support
object-oriented programming features and still retain the power and elegance of C. Therefore
C++ is an extension of C with a major addition to the original C language. C++ is a superset of
C. Most of what we already discussed in C applies to C++ also. Therefore almost all C programs
are also C++ programs with few minor differences. The most important facilities that C++ adds
on to C are classes, inheritance, function overloading and operator overloading. These
features enable you to create abstract data types, inherit properties from existing data types and
support polymorphism, then making C++ a truly object-oriented language.

A Simple C++ Program


12

A simple example of a C++ program that prints a string on the screen.


Program 1: Printing a string on the screen
#include <iostream>

//header file

using namespace std;


int main()

//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.

Features of a C++ Program


Like C, the C++ program is a collection functions such as main() as in above example.
Every program must have a main() and execution begins from main(). C++ is a free-form
language. Like C, the C++ statements terminate with semicolon.

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.

Ex. /* this is an example program


For learners */
Note: We can use either or both styles in our programs.
13

The iostream File:


The first line in the program
# include < iostream>
Causes the preprocessor to add the contents of the iostream file to the program. The
iostream file contains declarations for the identifiers cout and cin and the operators << and
>>. The file should be included at the beginning of all programs that use input/output
statements.

Return Type of main ( ):


In C++, main() returns an integer type value to the operating system. Therefore, every
main() in C++ should end with a return (0) statement, otherwise, a warning or an error might
occur. Since main() returns an integer type value, return type for main() is explicitly specified as
int.
Example:
int main( )

//main return integer

{
----------;
-----------;
-----------;
return 0; //return zero statement
}

Input and output statements:


Output Operator:
The syntax of cout statement
cout<<string ;
Example: cout<<Welcome to C++ language for students\n; //one form of cout statement
The string in quotation marks to be displayed on the screen. The cout is a predefined object that
represents the standard output stream (i.e., screen in this case) in C++. The operator << is
called the insertion or put to operator. It inserts (or sends) the contents of the variable on its
14

right to the object on its left. This corresponds to familiar printf() operation in C.
Screen

C++

<<

cout
Object

Insertion Operator

Variable

Figure:Output using insertion operator


The object cout has a simple interface. If string represents a string variable, then following
statement will display its contents.
cout<<variable_name; //Another form cout statement
This statement prints the value of that particular variable_name on output screen.

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.

Cascading of input/output operators:


In the statement
cout<<Another form of cout statement is:<<variable_name<<\n;
we used insertion operator << repeatedly for printing the result. First we send the string
Another form of cout statement is:to cout and then send the value of variable_name. Finally,
it sends the new line character so that the next output will be in the new line. The multiple use of
<< in one statement is called cascading.
Similar to << the extraction operator (>>) can also cascade.
cin>>variable_name1>>variable_name2;
The values are assigned from left to right. i.e., in an input 10 20 , 10 will be assigned to
variable_name1 and 20 will be assigned to variable_name2.
Note: cin can read only one word and therefore we cannot use names with blank spaces.
Program 2:Write a program to input integer, float, char, and string using cin statement and
display using cout statement.

#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;

//reading the values from keyboard

cout<<Enter the string:;


cin>>name;
cout<<The values are:\n;
16

cout<< i = <<i<< f = <<f<< ch = <<ch; //displaying the values on output screen


cout<<\n name = <<name;

return 0;

// return zero statement

}
Output:
Enter the integer, float and character: 3

6.5

Enter the string: RAJU&RAMESH


The values are:
i=3

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

cout<<Enter two numbers:;


cin>>num1;
cin>>num2;
float sum;

//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

Sum is: 8.6


Average is: 4.3
Note: The only disadvantage of this style of declaration is that we cannot see all the variables
used in a program at a glance.

Structure of C++ program


A typical program contains 4 sections as shown below.

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:

Like C, C++ programs also depends upon some header files.

For example #include<iostream>


18

2) Class Declaration or Definition:

A Class contains variables declaration, functions declaration/definition.

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

3) Class function definitions:

The class function definition can be done outside or inside the class declaration.

If function is small then define inside the class.

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.

Dynamic Initialization of Variables


In C a variable must be initialized using a constant expression, C++ permits initialization
of the variables at run time using expressions at the place of declaration. This is referred to as
dynamic initialization.
Example:
int n = strlen(string);

//In this n is initializing at run time

float area = 3.14 * r * r ; //In this area

19

Program 4: Write a program in c++ to demonstrate dynamic initialization.


#include<iostream>
using namespace std;
int main( )
{
cout<<Enter radius :;
int r;
cin>> r ;
float area = 3.14 * r * r ;//variable area is declared & assignment is carried out at run
cout<< \n Area = <<area;

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];

// is alias for 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;

//x is incremented so also m

}
int main()
{
int m=100;
21

cout<<\n before call of function <<m;


fun(m);

//function call

cout<<\n After call of function <<m;


return 0;
}

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.

::

scope resolution operator

::*

pointer-to-member declarator

->

pointer-to-member operator

.*

pointer-to-member operator

delete memory release operator


new

memory allocation operator

endl

line feed operator

setw

field width operator

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.

Scope Resolution Operator (: : )


C++ supports a mechanism to access a global variable from a function in which a local
variable is defined with the same name as a global variable. It is achieved using the scope
resolution operator. The syntax of accessing a global variable using scope resolution operator
is:
Syntax:

:: 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;

//accessing local variable

cout<<Global=<<::num;

//accessing global variable

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.

Member Dereferencing Operators


C++ permits us to define a class containing various types of data and functions as
members. You can access class members through pointers. In order to achieve this, C++ provides
a set of three pointer-to-members operators.
They are:
1.

::*

It is used to declare a pointer to a member of a class.

2.

.*

It is used to access a member using object name and a pointer to that


member.

3.

-->*

It is used to access a member using a pointer to the object and a pointer to


that member.

Runtime Memory Management


Whenever an array is defined, a specified amount of memory is set aside at compile time,
which may not be utilized fully or may not be sufficient. If a situation arises in which the amount
of memory required is unknown at compile time, the memory allocation can be performed during
execution. Such a technique of allocating memory during runtime on demand is known as
dynamic memory allocation.
C++ provides the two special operators to perform memory management dynamically

new operator for dynamic memory allocation

delete operator for dynamic memory deallocation

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;

//declaration of a pointer variable

p=new int;

//allocate two bytes of memory for p

*p=25;

2) We can also initialize memory using the new operator.


The general format for initialization is:
Pointer-variable = new data-type(value);
Example:
int *p;

//declaration of a pointer variable

p=new int(25);

//allocate two bytes of memory for p

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

arr = new int[n];

//dynamically allocate memory for an array of size n

arr[0]=10; //initialize the variables

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;

//delete data object p of integer

To release memory for an array the general format is


delete [size] pointer variable;

//where size is size of the array and it is optional

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

Program illustrating setw and endl


#include<iostream>
#include < iomanip.h >

// for setw

using namespace std;


int main ( )
{
int Basic = 950, Allowance = 95, Total = 1045;
cout << setw (10) << Basic << setw (10) << Basic << end1
<< setw (10) << Allowance << setw (10) << Allowance << end1
<< setw (10) << Total << setw (10) << Total << end1;
return 0;
}
Output:
Basic

950

Allowance
Total

95
1045

Type Cast Operator


C++ permits explicit type conversion of variables or expressions using the type cast
operator.
The following two versions are equivalent:
27

(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.

Difference between Class & Structure:


A structure in C is a collection of similar or dissimilar data types. C++ extends the reach
of structures by allowing the inclusion of even functions within structures.

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 structures to exclusively hold data.

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.

Objects of classes can call another without dot operator.

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.

Syntax of Class Declaration:

class

<class-name>

29

The functions and the variables collectively called class members.


The variables declared inside the class are known as data members and functions are member
functions.
The class members are generally grouped under two sections called private and public.
(These are the two access specifiers (or) visibility labels in C++). By default all members in
class is private i.e no external use of it. Where as in public we can access then even from out
side the class.

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

// ends with semicolon.

(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

// ends with semicolon.

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;

This variablename is nothing but object of type classname.


Example:
item

x;

We may also declare more than one object in one statement.


item x , y , z ;
Objects can also be created when a class is defined by placing their names immediately
after the closing brace, as we do in case of structures.
Example:
class item
{
------------------------------------------------------------}x,y,z;

// here x , y , z are objects

3. Accessing Class Members:


The private data of a class can be accessed only through the member functions of that
class.

The following is the format for calling a member function:


object_name . function_name ( actual_arguments);

Example:
class item
{
int number;

// variable declaration

float cost;

// private by default

public:
32

void getdata (int a, float b); // functions declaration


void putdata (void);

// using prototype

};
Accessing members:
item x;

// x is object

x.getdata( 10, 25.5 );


similarly
x.putdata( );
Note: 1) Remember a member function can be invoked only by using an object(of the
same class).
2) The statement like

getdata( 20, 15.5 ) has no meaning.

Similarly x.number=100 is also illegal. Although x is an object of the type item to


which number belongs to private member can be accessed only through a member
function and not by the object directly.

Defining a Member Functions


Member function can be defined in two places:
1. Outside the class definition.
2. Inside the class definition.
It is natural that, irrespective of the place of definition the function perform the same
task. Therefore the code for the function body would be identical in both the cases. But there is
difference in function header.

1 Outside the class definition:


Member functions that are declared inside a class have to be defined separately outside
the class. Their definitions like are as normal functions. They should have a function header and
a function body.

33

Difference between member function & normal functions:


The important difference between a member function and a normal function is that a
member function incorporates a membership identity label in the header. This label tells the
compiler which class the function belongs to.
Syntax on general form of a member function:
return-type

class-name : : function-name (arguments declaration)

{
Function-body
}

Note:- The scope of the function is restricted to the class name specified in the header
line.

: : is called the scope resolution operator.


Example:
void item :: getdata (int a, float b) // member function definition
{
number = a;
cost = b;
}
void item :: putdata ( )
{
cout<<number:<<number<<\n;
cout<<cost:<<cost<<\n;
}
Characteristics of member function:

Several different classes can use the same function name.

Member functions can access the private data of the class.

(A non member function can not do so)

A member function can call another member function directly, without dot operator.

34

2 Inside the class definition:


Another method of defining a member function is to replace the function declaration by
the actual function definition inside the class.
Example:#include<iostream>
using namespace std;
class item
{
private:
int number;
float cost;
public:
void getdata (int a, float b);
void putdata ( )
{
cout<<number<<\n;
cout<<cost<<\n;
}
}; //end of the class

35

// declaration

A C++ program with class Access Specifiers


#include <iostream>
using namespace std;
class item
{
int number; // private by default
float cost;
public:

// access specifier

void

getdata (int a, float b); // prototype declaration

void

putdata ( ) // function defined inside class

{
cout<<number:<<number<<endl;
cout<<cost:<<number<<\n;
}
};

//end of the class

// member function definition outside the class


void

item :: getdata (int a, float b)

{
number = a;

// private variables directly used

cost = b;
}
int main ( ) //main function with return int
{
item x;

//object created

cout<<\n object x<< \n;


x.getdata(100, 299.5);

// call member functions

x.putdata( ) ;
item y;

// another object is created

cout<<\n object y<<\n;


y.getdata (200, 45.75);
36

y.putdata( );
return 0;
}

// return zero statement

// end of main

Output:
object x
number:100
cost:299.5
object y
number:200
cost:175.5

Nesting of member functions


We discussed that a member function of a class can be called by an object of that class
using a dot operator. However, there is an exception to this.
A member function can be called by using its name inside another member function of
the same class. This is known as nesting of member functions.

Program: illustrates the nesting of member functions


#include<iostream>
using namespace std;
class set
{
37

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

Input values of m and n

25 18

Largest value = 25

Accessing private member functions:

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 ( );

// private member function

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

You might also like