You are on page 1of 92

OBJECT ORIENTED PROGRAMMING WITH C++

PREPARED BY S.KALAISELVI/R.KANAKARAJ/R.LATHA
*****************************************************************

SUBJECT DESCRIPTION:

This subject deals with Object–oriented programming concepts like Abstraction,


Encapsulation, Inheritance and Polymorphism.

GOAL:

Knowledge on Object–oriented concept and programming with C++.

OBJECTIVE:

To inculcate knowledge on Object-oriented programming concepts using C++.

UNIT-I:

Introduction to C++: key concepts of Object-Oriented Programming –Advantages


Object Oriented Languages – I/O in C++ - C++ Declaration.

Control Structures: Decision Making and Statements: if ..else, goto, break,


continue, switch…case statements. Loops in C++: for, while, do - Functions in C++ - Inline
functions – Function Overloading.

UNIT-II:

Classes and Objects: Declaring Objects – Defining Member Functions – Static


Member variables and functions – array of objects –friend functions – Overloading member
functions – Bit fields and classes – Constructor and destructor with static members.

UNIT-III:

Operator Overloading: Overloading unary, binary operators – Overloading Friend


functions – type conversion – Inheritance: Types of Inheritance – Single, Multilevel,
Multiple, Hierarchal, Hybrid, Multi path inheritance – Virtual base Classes – Abstract Classes.

UNIT-IV:

Pointers: Declaration – Pointer to Class, Object – this pointer – Pointers to derived


classes and Base classes. Arrays: Characteristics – array of classes – Memory models –
new and delete operators – dynamic object –binding, Polymorphism and Virtual Functions.

UNIT-V:

Files: File stream classes – file modes – Sequential read / write operations – Binary
and ASCII Files – Random Access Operation – Templates – Exception Handling – String:
Declaring and initializing string objects – String Attributes – Miscellaneous functions.

TEXT BOOK: 1. OBJECT-ORIENTED PROGRAMMING WITH C++, E.Balagurusamy,


1998, TMH.

REFERENCE BOOKS:

1. OBJECT-ORIENTED PROGRAMMING WITH ANSI AND TURBOC C++ - Ashok N


Kamthane, Pearson Education publication. 2003.

2. C++ PROGRAMMING Black Book, Steven Holzner, Wiley Student edition, Wiley
India.
3. DATA STRUCTURES USING C & C++, Yedidyah Langsam, Moshe J. Augenstein
&Aaron M. Tanenbaum, 2nd edition, PHI.

UNIT – I

C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose


programming language. It was developed by Bjarne Stroustrup starting in 1979 at Bell Labs
as an enhancement to the C language and originally named C with Classes. It was
renamed C++ in 1983.

The language began as enhancements to C, first adding classes, then virtual


functions, operator overloading, multiple inheritance, templates, and exception handling
among other features. After years of development, the C++ programming language
standard was ratified in 1998 as ISO/IEC 14882:1998. That standard is still current, but is
amended by the 2003 technical corrigendum, ISO/IEC 14882:2003.

The next standard version (known informally as C++0x, in reference to the long-
standing expectation that it would be released sometime before 2010) is in development; its
final draft was approved on March 25, 2011 and the formal specification is expected to be
published in the summer of 2011.

INTRODUCTION TO C++:

Object – oriented programming language is a feature that allows a mode of


modularizing programs by forming separate memory area for data as well as functions that
is used as object for making copies of modules as per requirement.

KEY CONCEPTS OF OBJECT ORIENTED PROGRAMMING

There are 12 basic concepts.

1. Object

2. Classes

3. Method

4. Data abstraction

5. Encapsulation

6. Inheritance

7. Polymorphism

8. Dynamic binding

9. Message passing

10. Reusability

Object

Objects are runtime entities in oop.

The selected program objects must be similar to real time objects. Objects occupy
space in memory. Every object has its own properties.

Ex., Book, Pen, table

Class
A class is grouping up of objects having identical properties, common behavior, and
shared relationship.

Ex: class: car

Properties: Company, model, color.

Actions: Speed (), average ().

Method

An operation required for an object or entity when coded in a class is called a


method.

All objects in a class perform certain common actions or operations. Each action needs an
object that becomes a function of the class that defines it and referred to as a method.

Class a

private:

Data member1; Members


Data member2;

public:

method1();
Member function or method
method2();

};

Data Abstraction

Abstraction directs to the procedure of representing essential features without


including the background details.

Encapsulation

The packing of data and function into a single component is known as encapsulation.

Inheritance

Inheritance is the method by which objects of one class get the properties of an
another class.

In this example class B get the properties from the Class A same as C.
Fig 1. Types of Inheritance

Types of Inheritance

 Simple inheritence

 Multilevel inheritance

 Hirarchical inheritence

 Multiple inheritance

 Hybrid inheritance

Polymorphism

Polymorphism allows the same function to act differently in different classes.

Line

Display()

Dotted Object Single Object Dash Object

Display(dotted) Display(single) Display(dash)

Fig 2: Polymorphism

Dynamic Binding

Binding means connecting one program to another program that is to be executed in


rely to the call. It also known as late binding.

Message Passing

OOP includes objects which communicate with each other. Programming with these
objects should be followed in steps shown below:

1. Declaring classes that define objects and their actions.

2. Declaring objects from classes

3. Implementing relation between objects.


Object . display(argument);

Object  object

.  communication operator

display  message

argument  data

Reusability

OOP allows reusability of the classes by extending them to other classes using
inheritance. Once the class is defined, the other programmer can also use it in their
programs and add new features to the derived classes. The main advantage is it saves the
time.

Example:

In the following example class A reused and class B is created. Again class B is
reused and class C is created.

Class A

Class A

Fig 3. Reusability Class A


Delegation

In OOP, two classes can be joined either by – inheritance or delegation, which


provide reusability of the class.

Real-time examples:

Class

Car Vs Class

Car: Collection of several properties like staring, break, clutch, etc each things are
used for particular purpose, all these properties are differ from each car like some car have
power staring ,however we have called it’s a car.

Class: it’s a collection of functions and variables. The functions and variables are
differing from each class. Each function is used for particular purpose however we have
called it’s a class

Object

Car Key Vs Object

Car Key: key is used for run the car. So many dummy keys can use for run a car.

Object: Object is used for run the class or invokes the class. So many objects can
create for a single class.

Birds Vs Abstractions
Birds: we invented flight based on the mechanism of Birds. So flight is derived form
the base of birds.

Abstraction: Abstraction is a way to remove the association of the behavior of an


object with the actual details behind the scenes which implement that object's behavior.
This 'abstraction' is usually accomplished through the use of base classes with virtual
functions; each derived function provides the details that implement the behavior behind
that abstraction.

Pen Vs Encapsulation

Pen: Ink is the important component in pen but it is hiding by some other material

Encapsulation: is a process of binding or wrapping the data and the codes that
operates on the data into a single entity. This keeps the data safe from outside interface
and misuse. One way to think about encapsulation is as a protective wrapper that prevents
code and data from being arbitrarily accessed by other code defined outside the wrapper.

Crocodile Vs Polymorphism

Crocodile: live indifferently on land or in the water. In water it’s Moment very fast
compare to land. An animal lives in different character in different place.

Polymorphism: a single function or single operator has different character in


different place.

Human heredity Vs Inheritance

Human heredity: The genetic transmission of characteristics from parent to


offspring. The sum of characteristics and associated potentialities transmitted genetically to
an individual organism

Inheritance: The new classes, known as derived classes, take over (or inherit)
attribute and behavior of the pre-existing classes, which are referred to as base classes (or
Parent classes). It is intended to help reuse existing code with little or no modification.

ADVANTAGES OF OOP:

1. Object oriented programming provides many advantages to the programmer


and the user.

2. Oops can be comfortably upgraded.

3. Using inheritance, redundant program codes can be eliminated and the use of
previously defined classes may be continued.

4. The technology of data hiding facilitates the programmer to design and develop
safe programs that do not disturb code in other parts of the program.

5. The encapsulation feature provided by OOP languages allows programmer to


define the class with many functions and characteristic and only few functions
are exposed to the user.

6. All OOP languages can create extended and reusable parts of programs.

7. Oops enhances the thought process of a programmer leading to rapid


development of new software in short span of time.

OBJECT – ORIENTED LANGUAGES


There are many languages which supports OOP

 C++

 Smalltalk

 Charm ++

 Java

Smalltalk

Smalltalk is purely an object –oriented programming language. Smalltalk programs


are considered to be faster than C++ and needs longer time to learn. Smalltalk programs
are written using Smalltalk browser.

Charm++

It is also an OOP language. The language provides features such as inheritance,


strict type checking, overloading, and reusability. It designed in order to work efficiently
with different parallel systems, together with shared memory systems and networking.

Java

Java was developed by Sun Microsystems. It supports maximum of oop


characteristics. It is easier than c++. Java allows client server programming and is used for
internet programming.

I/O IN C++

Streams in C++

C++ supports a number of input/output operations to read and write operations. The
stream is an intermediator between I/O devices and the user.

Stream is flow of data In bytes in sequence. If data is received from input devices in
sequence is called source or input stream. When the data is passed to output devices then it
is called as destination stream or output stream.

Keyboard Monitor

Stream

Disk Disk
Fig 4. Streams and I/O devices

Predefined Streams

C++ has predefined streams. These streams are called as standard I/O objects.
These streams are automatically activated when the program execution starts.

cin standard input usually corresponding to stdin in c. it handles inputs from input
devices usually from keyboard.

Cout standard output corresponding to stdout in c. it passes the data to output


devices as monitor and printers.

Clog a fully buffered version of cerr. It controls error massages that are passed from
buffer to the standard error device.
Cerr standard error output corresponding to stderr in c. it controls the unbuffered
output data. It catches the error and passes to standard error device monitor.

Program for displaying pre defined objects.

#include<iostream.h>

#include<conio.h>

void main()

clrscr();

cout<<”\n streams”;

cerr<<”\nstreams”;

clog<<”\nstream”;

getch();

output:

streams

streams

streams

Stream Classes

C++ has a number of stream classes that are used to work with console and file
operations. These classes are called stream classes. All these classes are declared I the
header file iostream.h.

IOS

istream ostream streambuf

iosteam File buffer

Fig 5. Stream Classes

The fig describes isream and ostream are derived classes of base class ios. The class
contains member variable object streambuf. It places in buffer. Istream and ostream are
derived from ios class using inheritance concept. The classes istream_withassign,
ostream_withassign, iostream_withassign append appropriate assignment operators.

Formatted and Unformatted Data

Formatted Means Representation Of Data With Different settings as per


the user. The various settings that can be dons are number format width points etc
The data accepted or printed with default setting by the I/O function of the language is
know as unformatted data. For example, when the cin statement is executed it aske for a
number. The used enters a number in decimal. For entering decimal number or displaying
the number in decimal using cout statement the user won’t need to apply any external
setting. By default the I/O function represents number in decimal format. Data handled in
such a way is called as unformatted data.

Unformatted Console I/O Operations

Input and Output Operations

The input stream uses cin object to read data and the output stream uses cout
object to display data on the screen. The cin and cout are predefined streams for input and
output of data. The data type is identified by these functions using operator overloading of
the operators << and >>. The operator << is overloaded in the ostream class and the
operator >> is overloaded in istream class.

Input stream

Input stream does read operations through keyboard. It uses cin as object. The cin
statement uses >> before variable name.

Syntax :

cin>>variable;

Example :

int a;

cin>>a;

The operator >> accepts the data and assign it to the memory location of the
variable. Each variable requires >> operator.

Output Stream

The o/p stream manages output of the stream. It uses << insertion operator before
variable name. It uses the cout object to perform console write operation.

Syntax:

cout <<variable;

Example :

int n;

cout<<variable;

Typecasting With cout Statement

Type casting refers to the conversion of data from one basic type to another by
applying external use of data type.

Program for Typecasting

#include<iostream.h>

#include<conio.h>
void main()

clrscr();

int x=77;

char y=’A’;

cout<<”x =”<<(char)x<<endl;

cout<<”y =”<<(int)y<<endl;

getch();

Output: x=M

y=65

Table 1: Typecasting Formats

Typecasting Output Conversion

cout<<(char)65; A int to char

cout<<(int)’A’; 65 char to int

cout<<(int)5.22; 5 float to int

cout<<(char)78.33; N float to char

123445338.33
cout<<(double) float to double
1.234453e+08

Signed to
cout<<(unsigned)-1; 65535
uunsigned.

C++ DECLARATIONS

Before writing a program it is necessary to know the rules of syntaxes of the


language. This enables a programmer to write error-free programs. The user makes many
mistakes if he/she does not know the rules and logics of the program.

Parts of C++ Program

Include files

Class declaration or definition

Class function definition

main() function

Fig 6. Parts of c++ program


A program consists of different sections. There are shown in the figure. Some of
them are optional and can be excluded from the program if required. C++ combines the
variable and functions in structure and classes. The structure and the class are same. The
functions may declare inside or outside the class.

I) include files section

C++ program depends upon the header files and function definition. Each header file
has an extension .h. the file should included using # include directive as per the format
given below:

#include<iostream.h> or #include”iostream.h”

All the definitions and prototypes of function defined in this file are current program.
This header file also gets complied with the original program. The header files are included
at the top of the program so that can be accessible from any part of the program.

II) Class declarations and definitions

We can also declare the class after the main function. But it is better to declare it
before main() function. Class definition is always terminated by a semicolon. Function
prototype declaration reports to the complier’s name, return type and required argument
list of the function.

Example : float sum(float,float)

III) Class function definition

The function definition can be done outside or inside the class. The function defined
inside the class are implemented as inline function.

IV) The main() function

C++ programs always start execution from the main() function.


UNIT - II

Types of Tokens

The c++ programs contain various components. The components identify them as
tokens.

The tokens are listed below,

 Keyword

 Variables

 Constants

 Special character

 Operators

Keywords

The c++ keywords are reserved words by the compiler and fixed meaning. There are
63 characters in c++ and turbo c++ permits 14 extra keywords. Some compliers won’t
accept variable names that exactly match to the keywords.

Table 2 : List of keywords

and default noexcept template

and_eq delete not this

alignof2 double not_eq thread_local2

asm dynamic_cast nullptr throw

auto1 else operator true

bitand enum or try

bitor explicittodo or_eq typedef

bool export private typeid

break externtodo protected typename

case false public union

catch float register using1

char for reinterpret_cast unsigned

char16_t2 friend return void

char32_t2 goto short wchar_t

class if signed virtual

compl inline sizeof volatile

const int static while

constexpr2 long static_assert2 xor

const_cast mutable static_cast xor_eq

continue namespace struct

decltype2 new switch


Identifiers

Identifiers are the names of variable, function and arrays etc, there are user defined
names, consisting of a sequence of letters and digits, with a letter as a first character.
Lower case letters are preferred. Upper case letters also permitted. The underscore symbol
can be used as an identifier.

Rules of identifier:

 The identifier name must begin with a character and should not start with a
digit, no space between characters. Underscore is valid.

 Name should not be a c++.

 It may be a combination of upper and lower case letters. Ex ., suM. Sum. These
are not same.

Variable Declaration and Initialization

Variable

A variable is used to store values. Each variable has memory location. The memory
locations are used to store the values of the variables.

Variable declaration

C++ permits declaration of variable any where inside the program. This makes the
programmer more comfortable to declare the variables.

Syntax:

(a) Data type v;

(b) Data type v1, v2,..vn;

The identifier v is a variable. Statement (a) declares the one variable and (b)
indicates more than one variable.

Example:

(a) int a;

(b) float a,b,c;

Initialization

Assigning a value to a variable is called as initialization. When the variable is


assigned the garbage value is removed and replaced with the given value. The declaration
of variable is done only once but initialization of variable can be done no of times. When a
new variable is assigned the previous value is replaced with new one.

Syntax:

Data type variable= value;

Ex:

int x=10;

Example Program:

#include<iostream.h>

#include<conio.h>
void main()

int x; //declaring the variable

int y=20; //declaring the variable with assigning value

x=10; //initializing the variable

cout<<”x=”<<x;

cout<<”y=”<<y;

x=y=20; //assigning value to more than one variable

cout<<”x=”<<x;

cout<<”y=”<<y;

getch();

Output:

x=10

y=20

x=20

y=20

Dynamic initialization

The dynamic initialization is always accomplished at the run time.

Ex:

#include<iostream.h>

#include<conio.h>

void main(){

int r;

float area;

cin>>r;

area= 3.14*r*r; //dynamic initialization

cout<<”Area is “<<area;

Data Types in C++

Data is a collection of characters, digits, symbols etc. it is used to represent the


information. The data types are classified in various types,

There are,

(a) Basic data types

(b) Derived data types

(c) User defined data types


(d) Void data type

Basic data types

The basic data types described below,

Table: 3 Basic Data types

Datatype Size in bytes Range

char 1 -128 to 127


unsigned char
1 0 to 255
signed char
1 -128 to 127
int
2 -32768 to 32767
unsigned int
2 0 to 65535
signed int
2 -32768 to 32767
short int
2 -32768 to 32767
unsigned short int
2 0 to 65535
signed short int
2 -32768 to 32767
long int
4 -2147483648 to 2147483647
signed long int
4 -2147483648 to 2147483647
unsigned long int
4 0 to 4294967295
float
4 3.4E-38 to 3.4E+38
double
8 1.7E-308 to 1.7E+308
long double
10 3.4E-4932 to 1.1E+4932
enum
2 -32768 to 32767
bool
1 true / false

Derived data types

The derived data types are of following types,

(1) Pointers

(2) Functions

(3) Arrays

(4) References

(1) Pointers

A pointer is a memory variable that stores a memory address. Pointer can be


declared in the same fashion as the other variables are declared. It denoted by ‘*’ operator.

int *x;

float *f;

Example ., program using pointers

#include<iostream.h>
void main(){

int x=2,*p;

cout<<”\n Address of x = “<<&x;

p=&x;

cout<<”value of x = “<<*p;

Output:

Address of x= 4096

Value of x = 2

Variable X 4096 2

Pointer variable P

Fig.6 -Pointers

Here x is a integer variable and *p is an integer pointer. The first cout statement
displays the address of variable x. the address of x is assigned to pointer p. the variables
are always used to store address of another variable. Second statement displays the value
of x using pointer p.

Functions

A function is a self contained block of codes. It is possible to use the same name with
multiple definitions called as function overloading.

Ex :

funA() and funB() are two user defined functions. These are invoked from the body
of main. After execution of the funA(), funB() the program control returns back to the
calling function main().

#include<iostream.h>

void main()

void show();

show();

void show()

cout<<”In function show()”;

OUTPUT:

In function show()
(3) Arrays

Array is a collection of elements of similar data type in which each element is


located in separate memory location.

Ex

int b[2];

b variable contains 2 values of integer data type.

#include<iostrream.h>

void mai()

int b[2]={2,4};

cout<<”b[0] value =”<<b[0];

cout<<”b[1] value = “<<b[1];

output:

b[0] value : 2

b[1] value : 4

(4) References

C++ reference types, declared with & operator are nearly identical but not exactly
same to pointer types. They declare alias for object variables and allow the programmer to
use variable by reference.

User Defined Data Type

User defined data types are of the following types,

(1) Structures and classes

(2) Union

(3) Enumerated data types

(i) Structure and classes

The struct is a keyword and used to combine variables of different data types into a
single record.

Syntax:

struct struct_name

data type variable1;

data type varaible2;

}struct variable declaration;

struct : Keyword

struct name : An optional tag name that defines the structure type.

structure variable : these are member variables and hold data.


Ex:

#include<iostream.h.

void main()

struct my_friend

char name;

int phone;

} A,B;

A.name=”Kumaran”;

A.phone=262312;

B.name=”Senthil”; Output : Kumaran

B.phone=267890; 262312

cout<<A.name; Senthil

cout<<A.phone; 267890

cout<<B.name;

cout<<B.phone;

Class

The class keyword is introduced in c++. It is use same as structure.

Syntax

class keyword class_name : baseclasslist

Member variable list;

class keyword : It is one of the keywords class, struct or union

class name : It can be any unique name inside its scope.

Baseclasslist : if the class is derived class, then it follows the list of the base
class.

Member variable list : Defines the data member variables and member
functions

Example

Class circle

int radius; //data member

int area(); //member function


};

(2) Union

A union is same as compared to a struct, the only difference is sharing the memory
space for the variables.

Syntax:

union unionname

data type variable name;

}union variable name;

Example

union chartoint

char c; //data member

int i;

};

C++ will allocate sufficient storage in union variable number to hold the big element
in the union. The union member variable number .c and .i uses the same memory location
in memory location in memory.

Ex,

In struct it allocate the memory as like this,

Data type Memory

int (2 bytes)

char (1 byte)

In union the allocation will be,

char

int
Anonymous unions

An anonymous union does not contain tag name. each element of such union can be
accessed without using tag name.

union

int k;

};
(3) Enumerated data type

The enum is a keyword. It is used for declaring enumeration data type. The
programmer can declare the new data type and define the variables of these data types that
can hold.

Example:

enum logical { false, true};

enum components{solid, liquid, gas};

#include<iostream.h>

void main()

enum logical { false, true};

cout<<”true : “<<true<<” false : “ <<false;

output :

true :1 false : 0

The void data type:

The void type is an empty data type. It can be used in two ways.

a. When specified as a function return type, void means that the function does
not return a value.

void message(char *name)

cout<<name;

here message() is a void function. The keyword is preceded by the function


name. When the function is executed it doesn’t return any value to the calling
function.

b. The void keyword is also used as argument function. When found in a function
heading void means that the function does not take any arguments.

int fun(void)

{ return 1

fun() does not require any argument.

c. when specified as a function return type and in function heading i.e, the
function neither returns a value nor require any argument.

void fun(void);

Type Modifier

The keywords signed, unsigned, short, and long are type modifiers. The type
modifiers change the meaning of the base data type to produce a new data type.
1. Each of these type modifiers is applicable for int.

2. signed and unsigned applicable for base type char.

3. long applied to double data type.

Example :

Long 1;

Unsigned char c;

Signed int s;

Unsigned for long int u;

Type casting

Definition

Type casting refers to the conversion of data from one basic type to another by
applying external use of data type.

There are two types

1. Explicit

2. Implicit

( 1 ) Explicit conversion

The desired type can be achieved by typecasting a value of particular type. It is done
using type casting operator. The complier is instructed to do conversion using typecast
operator.

Data type name (expression)

Example:

x=5/float(2);

float x;

x=(int) 5/2.0;

The above expression returns the value 2.5, even if an int typecast operatoris used.
The typecast operator attempts to make the expression int type, but the expression
contains float type operand. Hence it is considered as float type expression and returns the
result of float type.

Program for explicit type conversion

#include<iostream.h>

void main()

clrscr();

cout<<int(17.78);

Output:

17
( 2 ) Implicit Type conversion

The type conversion is carried out when the expression contains different types of
data items. When the compiler carries such type conversion itself by using inbuilt datatypes
in routines then it is called imlicit type conversion.

 The variable of lower data type converted into higher data type is called as
promotion.

 When the variable of higher datatype converted into to lower type, is called as
demotion.

Implicit type conversion rules

Argument 1 Argument 2 Output

Char int int

int float float

int long long

double float double

int double double

long double double

int unsigned unsigned

Table: 4 - Implicit type conversion

Program for implicit type conversion

#include<iostream.h>

#include<conio.h>

void main()

int j=2.54;

int k=’A’;

char c=87.5;

cout<<”j=”<<j;

cout<<”\n k=”<<k;

cout<<”\nc=”<<c;

Output:

J=2

K=65

C=w

Constants
The constant values do not change during execution of the program. In C++ there
are two types of constants.

1. Literal

2. Symbolic

(1)Literal constant

A literal constant is directly assigned to a variable.

int x= 5;

Here the x value doesn’t change when the program is executed.

Example Constant type

542 Integer type

35.254 Floating point constant

0x54 Hexadecimal constant

0171 Octal integer constant

‘c’ Character constant

“C plus plus” String constant

L “xy” Wide character constant

Table: 5 Literal constants

(2) Symbolic constant

A symbolic constant is defined in the same way as variable.

There are three ways:

Ways Example

#define # define price 152

The const keyword const int price=152

The enum keyword enum days { ‘Friday’,’Monday’}

Table: 6 Symbolic constants

Program for symbolic constant and litral constants

#include<iostream.h>

void main()

const Sunday=0;

const Monday=1;
int c=30;

cout<<”\n Enter day (0&1) :”;

cin>>c;

if(c==Sunday && c!== Monday)

cout<<”\n Holiday”;

else

cout<<”\nWorking day”;

cout<<” Literal constant \n c=30”;

Output:

Enter day (0&1) : 0

Holiday

Literal constant \n c=30

Operators in C++

Operator is an instruction to the compiler o interpreter, specified by a single or


double symbol to perform certain operations with constans.

Example:

5+10

Here, 5 and 10 are constants. The symbol + is an operator that indicates the
operation to be performed and performs addition of numbers and is a single operator.

Types of operators is given below,

1. Arithmetic operator

2. Relational operator

3. Logical operator

4. Assignment operator

5. Increment or decrement operator

6. Conditional operator

7. Bitwise operator

8. Special operator

Table: 7 Types of operators & C++ operators

Types of operator Symbolic representation

Arithmetic operators +, -, *, /, %
Relational operator <,>,= = , <=,>=,and !=

Logical operator &&, ||, !

Increment operator or decrement ++ and –


operator

Assignment operator =

Bitwise operator &,|,^,>>,<< and ~

Special operator ,

Conditional operator ?:

Operator description

<< insertion operator

>> extraction operator

:: Scope resolution operator

:: * pointer to member declaration

->* dereference pointers to pointers to class members

.* dereference pointers to class members

delete memory release operator

New memory allocation operation

Precedence of Operators In C++

C++ operators are classified into 17 groups as shown in table. The operators with in
each category have equal precedence.

The following operators cannot be overloaded.

. c++ direct component selector


.* c++ dereference
:: c++ scope access/ resolution
?: conditional operator

Precedenc
Operator Description Overloadable Associativity
e
1 :: scope resolution no left to right
() function call yes
2 [] array access yes left to right
-> member access yes
. no
++ -- postfix yes
dynamic_cast
static_cast
type conversion no
reinterpret_cast
const_cast
typeid Get type information no
! not logical negation yes
bitwise negation
~ compl yes
(complement)
++ -- prefix yes
+ - unary sign operations yes
* & indirection and reference yes
3 right to left
Size (of the type) of the
sizeof no
operand in bytes
new
new[] dynamic memory
yes
delete management
delete[]
(type) Cast to a given type yes
->* member pointer selector yes
4 left to right
.* member object selector no
5 * / %
arithmetic operations yes left to right
6 + -
7 << >> shift operations yes left to right
8 < <= > >=
relational operations yes left to right
9 == != not_eq
10 & bitand Bitwise AND yes left to right
11 ^ xor Bitwise XOR yes left to right
12 | bitor Bitwise OR yes left to right
13 && and logical AND yes left to right
14 || or logical OR yes left to right
Ternary conditional (if-
15 ?: no right to left
then-else)
= += -
16 = *= /= %= &= ^= |= assignment yes right to left
<<= >>=
Sequential evaluation
17 , yes left to right
operator

Table: 8 Precedence of Operators in C++

Preference of * and [ ] operator

a. int *arr[5];

The above statement declares an array of five pointers and following operations are
invalid. Because array name and address are constant. a++ ,++a.

b. int (*arr) [5]

The above declaration declares a pointer to an array of five elements. Hence the
operations such as arr++ and ++arr are not supported.

Referencing ( & ) and dereferencing (*) operators

These operators are used for referencing and dereferencing. The symbol is also used
in c++ to define reference types, and as a bitwise AND operator. We can also use the
astrick as an operator to dereference a pointer and as the multiplication operator.
Referencing operator ( & )

This operator is used for define referencing variable. A reference variable prepares
an alternative name for previously defined variable.

Syntax:

Data type &reference variable name = variable name

Example :

int qty = 10;

int &qt=qty;

In this example,

int  data type

&  reference

qt  variable name

Principles for declaring reference variable

1. A reference variable should be initialized.

2. Once a reference variable is declared, it should not refer to any other variable. Once
the actual variable and reference variable are connected they are tied jointly
congenitally.

3. The reference variable can be created referring to pointer variable. The declaration
would be as given below:

Char *h =” C++”;

Char *&q=h;

4. A variable can contain various references. Modifying the value of one of them results
in a change in all others.

5. Array of references is not allowed.

Dereferencing operator

The asterisk (*) is a variable expression used to declare a pointer to a given type. If
the operand is a pointer to function, the result is a function designations. If the operand is a
pointer to an object, the result is an lvalue, indicating that object. The following conditions,
the result of indirection is undefined.

1. The expression is a null pointer.

2. The expression is the address o an automatic variable and execution and it is out of
scope.

The difference is & displays address of the variable in the RAM and * displays the
value of the variable.

Scope access operator

The declarations of the same variable refer to different memory locations. The block
of the C++ program from where the variable can be accessed is known as the scope of the
variable.
The scope access operator :: allows a programmer to access a global name even if it
is hidden by a local re declaration of that name.

#include<iostream.h>

int a=10;

main()

Int a=20;

cout<<”::a= “<<::a<<”\t a=”<<a;

Output:

::a=10 a=20

Memory Management Operators

C++ supports following memory management operators,

malloc()

calloc()

realloc()

free()

new()

delete()

malloc()

Allocates a block of size bytes of memory, returning a pointer to the beginning of


the block.
calloc()
Allocates a block of memory for an array of num elements, each of them size bytes
long, and initializes all its bits to zero.
realloc()

Reallocating a memory size

Free()

Deallocate space in memory

Followings are the advantages of new operator over the


function malloc().

 The new operator itself calculates the size of the object without the use of
sizeof() operator.

 It returns the pointer type. The programmers need not take care of its
typecasting.

 The new operator allocates memory and initializes the object at once.

 The new and delete operators are very easy in syntax. They can be
overloaded.
new operator

Allocates memory of specified type and returns back the starting address to the
pointer memory variable. Here element size is optional. If the new operator fails to allocate
the memory it returns null, which can be used to detect failure or success of new operator.

Syntax:

Pointer memory variable = new data type [size];

Example:

Pv= new int; //pointer variable of integer type-contains starting value

int *Pv=new int(50); //pointer variable

*p= new int[3]; //array value it contains 3 integer type.

The delete operator

The delete operator frees the memory allocated by the new operator. This operator is
used when the memory allocated is no longer usable in the program.

Syntax:

a. delete pointer memory variable

b. delete [element size] <pointer memory variable>

Example

a. delete p;

b. delete [5]p or delete []p;

#include <iostream>
#include <new>
using namespace std;
{
struct myclass
{
myclass() {cout <<"myclass constructed\n";}
~myclass() {cout <<"myclass destroyed\n";}
};
int main ()
{
myclass * pt;
pt = new myclass[3];
delete[] pt;
return 0;
}

Output:

myclass constructed

myclass constructed

myclass constructed
myclass destroyed

myclass destroyed

myclass destroyed

Comments

In C++, a symbol // is used as a comment symbol and there is no termination


symbol. A comment can be inserted anywhere in the line and whatever follows till the end
of the line is ignored. C++ supports // and /**/ symbols for comment line.

Example

// This is a C++ comment line.

Comma operator

In C, every statement of the program is terminated by semi-colon(;). It is also


applicable in C++ and addition, C++ allows us to terminate a statement using comma
operator after satisfying the following rules:

1. The variable declaration statements should be terminated by semi-colon.

2. The statements followed by declaration statements like clrscr(), cin, cout can be
terminated by comma operator.

3. C++ permites declaration of variables at any place in program but such


declaration is not allowed in between the statements terminated by comma
operator. The initialization of priviously declared variables can be done.

4. The last statement of the program must be terminated by semi-colon.

Ex.

#include<iostream.h>

#include<conio.h>

void main()

clrscr(),

cout<<”Example for comma operator”;

CONTROL STRUCTURES IN C++

A program is usually not limited to a linear sequence of instructions. During its


process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides
control structures that serve to specify what has to be done by our program, when and
under which circumstances.

Most of the control structures that we will see in this section require a generic
statement as part of its syntax. A statement can be either a simple statement (a simple
instruction ending with a semicolon) or a compound statement (several instructions grouped
in a block), like the one just described. In the case that we want the statement to be a
simple statement, we do not need to enclose it in braces ({}). But in the case that we want
the statement to be a compound statement it must be enclosed between braces ({}),
forming a block.
if statement

The if keyword is used to execute a statement or block only if a condition is fulfilled.

Syntax:

if (condition) statement;

Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program
continues right after this conditional structure.

For example, the following code fragment prints x is 100 only if the value stored in
the x variable is indeed 100:

if (x == 100)

cout << "x is 100";

if we want more than a single statement to be executed in case that the condition is
true we can specify a block using braces { }

if (x == 100)

cout << "x is ";

cout << x;

The if keyword is used to execute a statement or block only if a condition is fulfilled.

if else statement

We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:
Syntax:

if (condition)

statement1;

else

statement2;
For example:

if (x == 100)
cout << "x is 100";
else

cout << "x is not 100";

Prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and
only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range
of values. The following example shows its use telling if the value currently stored in x is
positive, negative or none of them (i.e. zero):

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else

cout << "x is 0";

Remember that in case that we want more than a single statement to be executed,
we must group them in a block by enclosing them in braces { }.

else if Ladder

When a series of many conditions have to be checked we may use the ladder else if
statement which takes the following general form.

if(condition1)
statement 1;

elseif(condition2)

statement2;

elseif (condition3)

statement3;

else if (condition)

statement n;

else default

statement;

statement-x;

This construct is known as if else construct or ladder. The conditions are evaluated
from the top of the ladder to downwards. As soon on the true condition is found, the
statement associated with it is executed and the control is transferred to the statement – x
(skipping the rest of the ladder. When all the condition becomes false, the final else
containing the default statement will be executed.

Program for else if ladder

#include <iostream>
using namespace std;
int main()
{
int x;
for(x=0; x<6; x++)
{
if(x==1) cout << "x is one\n";
else if(x==2) cout << "x is two\n";
else if(x==3) cout << "x is three\n";
else if(x==4) cout << "x is four\n";
else cout << "x is not between 1 and 4\n";
}
return 0;
}
Output:

x is not between 1 and 4


x is one
x is two
x is three
x is four
x is not between 1 and 4

Nested if and if-else statements

The if-else statement allows a choice to be made between two possible alternatives.
Sometimes a choice must be made between more than two possibilities. For example the
sign function in mathematics returns -1 if the argument is less than zero, returns +1 if the
argument is greater than zero and returns zero if the argument is zero. The following C++
statement implements this function:

if (x < 0)

sign = -1;

else

if (x == 0)

sign = 0;

else

sign = 1;

This is an if-else statement in which the statement following the else is itself an if-
else statement. If x is less than zero then sign is set to -1, however if it is not less than zero
the statement following the else is executed. In that case if x is equal to zero then sign is
set to zero and otherwise it is set to 1.

Novice programmers often use a sequence of if statements rather than use a nested if-else
statement. That is they write the above in the logically equivalent form:

if (x < 0)

sign = -1;

if (x == 0)

sign = 0;

if (x > 0)

sign = 1;

LOOPS IN C++

Loops are basically means to do a task multiple times, without actually coding all
statements over and over again. Loops are used to repeat a block of code. Being able to
have your program repeatedly execute a block of code is one of the most basic but useful
tasks in programming -- many programs or websites that produce extremely complex
output (such as a message board) are really only executing a single task many times. (They
may be executing a small number of tasks, but in principle, to produce a list of messages
only requires repeating the operation of reading in some data and displaying it.) Now, think
about what this means: a loop lets you write a very simple statement to produce a
significantly greater result simply by repetition.

There are three types,

1. for loop

2. while loop

3. do while loop

for Loop

The for loop allows execution of a set of instructions until a condition is met.
Condition may be predefined or open-ended. Although all programming languages provided
by c/c++ is worth mentioning.

Syntax:

for(initialization; condition; increment/decrement)

Statement block;

 Intialization is an assignment statement that is used to set the loop control


variable(s).

 The condition is a relational expression that determines the number of the


iterations desired or the condition to exit the loop.

 The increment decides how to change the state of the variables.

 Three sections are separated by semi-colon.

Program for for loop

#include<iostream.h>

void main()

cout<<”Sample program for for loop”;

for(int i=0;i<=5;i++)

cout<<i<<”\n”;

Output:

Sample program for for loop

4
5

while loop

Syntax

while(condition)

Body of the loop;

The condition may be expression. The loop statements will be executed till the
condition is true.

Program for while loop

#include<iostream.h>

void main()

cout<<”Sample program for while loop”;

int i=0;

while(i<=5)

cout<<i<<”\n”;

i++;

getch();

Output:

Sample program for while loop

do-while loop

In this loop the condition is checked at the end.

Syntax:

do

{
Body of the loop;

}while(condition);

Program for do-while loop

#include<iostream.h>

void main()

cout<<”Sample program for do-while loop”;

int i=0;

cout<<i<<”\n”;

i++;

} while(i<=5);

getch();

Output:

Sample program for do-while loop

FUNCTIONS IN C++

Function is a self contained block of codes.

The Process of dividing a large program in to tiny sub program is called modular
programming.

Advantages of functions:

1. Support for modular programming.

2. Reduction in program size.

3. Code duplication is avoided.

4. Code reusability is provided.

5. Functions can be called repetitively.

6. A set of functions can be used to form libraries.

Parts of function

A function has following parts:

 Function prototype declaration

 Definition of a function
 Function call

 Actual arguments

 Formal arguments

 Return statement

Function prototype

A prototype statement helps the compiler to check the return and argument types of
the function. It contains return type, function name and argument list.

It tells the compiler,

a. The name of the function

b. The type of value returned

c. The type and number of arguments.

Example:

a. void show(void);

b. float sum(float ,int);

c. float sum(float x, int y);

Explanation

a. In example (a) the return type is void. The function won’t return any value.

b. In example (b) the return type is float and int.

c. In example (c) the return type is float and int with arguments.

Function definition

The first line of the function is called function declarator and is followed by function
body. The block of statements followed by function declarator is followed by function
declarator is called function definition.

Function call

A function is activated when a call to function is invoked. A function must be called


by its name, followed by arguments and semi colon.

Actual and formal arguments

The arguments declared in calling function are called actual arguments. The
arguments declared in called function are called formal arguments.

void main()

x=sum(y,z); Actual Arguments


}

float sum(float j, int k) Formal Arguments


{

return(j+k);}

The return type


The return statement is used to return value to the calling function. It returns one
value at a time.

Syntax : return (variable name); or return variable name;

Example:

#include<iostream.h>

#include<conio.h>

void main()

float sum (float, int);

float x,y=2.4;

int z=5;

x=sum(y,z);

cout<<”x value is “<<x;

float sum(float j, int k)

return (j+k);

Output:

x value is 7.4

void main()

float sum(float,int); Function Prototype

float x, y=2.4;
Actual arguments
int z=5;

x=sum(y,z); Function call


} Formal arguments
float sum(float j, int k)
Function declarator
{

return(j+k) Return statement

}
Function Body

Inline functions
When a function is declared as inline function, the compiler copies the function body
is inserted in place of function call during compilation. It increases the speed of the
execution. Repetitive function calls and returning values are removed.

Syntax:

inline function_name

statements; // function body

Example:

inline float square ( float k)

return (k*k);

Following are some situations where inline function may not work:

1. The function should not contain static variables.

2. The function should not be recursive.

3. Function containing control structure statements such as switch, if , for loop


etc.

4. The function main() cannot work as inline.

Program for inline function:

#include<iostream.h>

#include<conio.h>

#define SQUARE(v) v*v

inline float square(float j)

return (j*j);

void main()

clrscr();

int p=3,q=3,r,s;

r=SQUARE(++p);

s=square(++q);

cout<<”r=”<<r<<”\n s=”<<s;

Output:
r=25

s=16
Function overloading

Defining multiple functions with same name is known as function overloading. The
overloaded function must be different in its argument list and with different data types.

Example:

#include<iostream.h>

#include<conio.h>

int sqr(int);

float sqr(float);

main()

int a=15;

float b=2.5;

cout<<”square of a =”<<sqr(a)<<”\n”;

cout<<”square of b=”<<sqr(b)<<”\n”;

return 0;

int sqr(int s)

return (s*s);

float sqr(float j)

return (j*j);

Output:

Square of a = 225

Square of b = 6.25
UNIT III

CLASSES AND OBJECTS

Object

Objects are runtime entities in OOP.

The selected program objects must be similar to real time objects. Objects occupy
space in memory. Every object has its own properties.

Ex., Book, Pen, table

Class

A class is grouping up of objects having identical properties, common behavior, and


shared relationship.

Ex: class: car

Properties: Company, model, color.

Actions: Speed (), average ().

STRUCTURES IN C++

Syntax:

struct structure_name

variable1;

variable2;

};

In this syntax,

struct  Keyword.

Structure_name  name of the structure.

Example:

struct item

int codeno;

float prize;

int qty;

};

The object of structure item can be declared as follows:

struct item a,*b;

The operators (.) and () arrow are used to access the member variables of struct.
The (.) operator is used for simple object and () is used for pointer variable.

Syntax for accessing object

[Object name] [Operator] [Member variable name]


Object name  Name of the object.

Operator  (.) or ()

Member variable name  name of the variable

Example:

a.codeno

a.price

a.qty

bcodeno

bprice

bqty

CLASSES IN C++

Classes and structure are the same.

Syntax:

Class <name of class>

private:

declaration of variable;

prototype declaration of function;

public:

declaration of variable;

prototype declaration of function;

};

Example:

class item

private:

int codeno;

float prize;

int qty;

void values();

public:

void show();

};

The class is enclosed by curly braces and terminated by a semi colon. The member
function is divided in two sections, i.e. private and public. These are terminated by (:).
functions are declared in private section and data members are declared in public section.
DECLARING OBJECTS:

An object having following properties:

 It is individual

 It points to a thing, either physical or logical that is identifiable by the user.

 It holds data as well as operation method that handle data.

 It’s scope is limited to the block in which it is defined.

Example:

Item a,b,*c;

Item is a class name. a,b are the simple objects and *c is pointer to class.

Accessing class members

The object can access the public member variable and functions of a class by using
operator dot(.) and arrow ().

Syntax:

[Object name] [operator] [member name]

To have access to members of class item, the statement would be,

a.show(); // access for simple object

a is an object

show() is an member function

cshow(); //access for pointer object

The public keyword

The keyword public can be used to allow object to access the member variables of
class directly like structure. It is terminated by colon (:). the member variables and
declared followed by the public can be accessed directly by the object.

The private keyword

The private keyword is used to prevent direct access to member variables or function
by the object. The class by default produces this effect. The structure variables are
functions of struct from access the private keyword is used.

The protected keyword

The protected keyword is same like private. It was used in inheritance of class.

Example:

#include<iostream.h>

#include<conio.h>

struct item

private: //private section starts

int codeno;

float price;
int qty;

public: //public section starts

void show()

codeno=125;

price=195;

qty=200;

cout<<” Codeno=”<<codeno;

cout<<”\nprice =”<<price;

cout<<”\n quantity=”<<qty;

};

int main()

clrscr();

item one; //object declaraton

one.show(); // call to member function

return 0;

Output:

Codeno=125

Price=195

Qty=200

DEFINING MEMBER FUNCTION

The member function must be declared inside the class. They can be defined public
or private or inside or outside the class. The member function inside the class are treated as
inline function is small then it should be defined inside the class.

Member function inside the class

It can be declared in public or private.

Private member function

A member function of a class can invoke any other member function of its own class.
This called as nesting of member functions. This can be terminated by semi colon.

#include<iostream.h>

class A

private:
int v1=20;

public:

int v2=30;

cout<<” Varaible v1 is declared as private and value is =”<<v1;

void show()

cout<<” Varaible v2 is declared as public and value is =”<<v2;

};

void main()

A a1;

a1.show();

Output:

Variable v1 is declared as private and value is = 20

Variable v2 is declared as public and value is = 30

The function inside the class is considered as inline function. To define a function outside
the class following care must be takes,

 The prototype of function must be declared inside the class

 The function name must be preceded by class name and its return type
separated by scope access operator.

STATIC MEMBER VARIABLE AND FUNCTION

Static is a keyword and its value is initialized as zero in default. A static function is
only recognized inside the scope of the present class.

Syntax:

Static variable name;

Static function name;

Example:

static int c;

static void display();

STATIC MEMBER FUNCTION

When function is defined as static it can be access only member variables and
functions. The static keyword makes the function free from the individual object of the class
and its scope is global in the class without creating any side effect from other part of the
program.
The following points while declaring static function:

1. Just one copy of static member is created in the memory for entire class. All
objects of the class share the same copy of static member.

2. Static member functions can access only static data members or functions.

3. Static member functions can be invoked using class name.

4. It is also possible to invoke static member functions using objects.

5. When one of the objects changes the value of data member variables, the
effect is visible to all the objects of the class.

#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode(void)
{
code= ++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
int test::count;
int main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
return(1);
}
Output:

Count 2
Count 3
Object number 1
Object number 2
Object number 3

STATIC PRIVATE MEMBER FUNCTION

It invoked using static public functions

Program for private member function

#include<iostream.h>

class IDGenerator

private:

static int s_nNextID;

public:

static int GetNextID() { return s_nNextID++; }

};

int IDGenerator::s_nNextID = 1;

int main()

for (int i=0; i < 5; i++)

cout << "The next ID is: " << IDGenerator::GetNextID() << endl;

return 0;

Output:

The next ID is: 1


The next ID is: 2
The next ID is: 3
The next ID is: 4
The next ID is: 5

Static public member variable

It can be initialized in main() like other variable. The static member variable using
class name and scope access operator can be accessed.

Program for static public variable

#include<iostream.h>

int c=11;

class bita
{

public:

static int c;

};

int bita ::c=22;

void main()

clrscr();

int c=3;

cout<<”\n Class member c=” <<bita::c;

cout<<”\n Global variable c=” <<::c;

cout<<”\n Local Variable c= “ <<c;

Output:

Class member c= 22

Global variable c=11

Local variable c=33

ARRAY OF OBJECTS

Array is a collection of similar datatypes. Array can be of any data type including
user defined data type, created by using struct, class and typedef declarations. We can also
create an array of objects.

Program for Array of objects

#include<iostream.h>

#include<conio.h>

class player

private:

char name[20];

int age;

public:

void input()

cout<<”\n Enter player name :”;

cin>>name;

cout<<”Age :”;

cin>>age;
}

void display(void)

cout<<”\n player name : “ <<name;

cout<<”\n Age :<<age;

};

int main()

player cricket[3];

cout<<”\n Enter name and age of 3 players “;

for( int i=0;i<3;i++)

cricket[i].input();

for( int j=0;j<3;j++)

cricket[j].display();

return 0;

Output:

Enter name and age of 3 players

Enter player name : Karthik

Age : 14

Enter player name : Kathir

Age : 15

Enter player name : Deepika

Age : 14

Player name : Karthik

Age : 14

Player name : Kathir

Age : 15

Player name : Deepika

Age : 14
friend FUNCTIONS

c++ allows a mechanism, in which a non-member function has access permission to


the private members of the class. This can be done by declaring a non member function
friend to the class whose private data is to be accessed. Here friend is a keyword.

class ac

private:

char name[15];

public:

void read()

cout<<”\n Enter your name “: ;

cin>>name;

friend void showbal();// friend function declaration

};

void showbal(ac a)

cout<<”\n name”<<a.name;

int main()

ac k;

k.read();

showbal(k);

return 0;

Output:

Enter your name : saranya

Name : saranya

OVER LOADING MEMBER FUNCTIONS

Member functions are also overloaded in the same fashion as other ordinary
functions. Overloading is nothing but one function is defined with multiple definitions with
same function name in the same scope.

Program for overloading member function

#include<iostream.h>

class abc
{

public:

int num(int);

double num(double);

};

int abc::num(int x)

int ans;

ans=abs(x);

return(ans);

double abc::num(double d)

double ans;

ans=fabs(d);

return(ans);

int main()

clrscr();

abc n;

cout<<”\n Absolute value of -25 is “<<n.num(-25);

cout<<”\n Absolute value of -25.24 is “<<n.num(-25.24);

return 0;

Output:

Absolute value of -25 is 25

Absolute value of -25.24 is 25

CONSTRUCTORS AND DESTRUCTORS

C++ provides a pair of in built functions called constructors and destructors.

The constructors construct the object and destructor destroys the object. There are
opposite to each other. The compiler automatically executes this function.

The C++ run time arrangement takes care of this execution. When a object is
created constructor is executed. The programmer can also pass these values to the
constructor to initialize member variables with different values.

The destructor destroys the object. the only difference is that destructor is preceded
by ~ operator.
Syntax for Constructor

class_name()

Example for Constructor

B()

Syntax for Destructor

~class_name()

Example for Destructor

~B()

In this example B is the class name.

CHARACTERISTICS OF CONSTRUCTOR AND DESTRUCTOR

CONSTRUCTOR

1. It has the same name as that of the class it belongs.

2. It executed when an object is declared.

3. It has neither return nor void value.

4. The main function of a constructor is to initialize objects and allocate appropriate


memory.

5. Though constructors are executed implicitly they can be invoked explicitly.

6. It can have default and can be overloaded.

7. It constructor without arguments is called as default constructor.

CONSTRUCTOR

1. Destructor has the same name as that of the class it belongs to and preceded by ~
(tilde) symbol.

2. Like constructor the destructor does not have return type and not even void.

3. Constructor and destructor cannot be inherited, though a derived class can call the
constructors and destructors of the base class.

4. Destructor can be virtual but constructors cannot.

5. Only one destructor can be defined in the destructor. The destructor does not have
any argument.

6. The destructor neither has default values nor can be overloaded.


7. Programmer cannot access addresses of constructors and destructors.

8. Constructor and destructor can make implicit calls to operators new and delete if
memory allocation/ de allocation is needed for an object.

9. An object with a constructor or destructor cannot be used as a member of a union.

Application with Constructor

The initialization of member variables of class is carried out using consttructors. The
constructor also allocates required memory of the object.

Example

#include<iostream.h>

#include<conio.h>

class num

private:

int a,b,c;

public:

num(void); // declaration of constructor

num::num(void) //Defining of constructor

cout<<”Constructor is called”;

a=0;b=0;c=0;

main()

num x;

Output:

Constructor is called.

The above example class num has three member integer variables a, b and c, the
declaration of constructor can be done inside the class and definition outside the class. In
definition, the member variables of a class num are initialized to zero.

Constructor with Arguments

It is also possible to create constructors with arguments and such constructors are
called as paramaterized constructors. For such constructors it is necessary to pass values to
the constructor when object is created.

Example

#include<iostream.h>
#include<conio.h>

class num

private:

int a,b,c;

public:

num(int m); // declaration of constructor

num(void); // declaration of constructor

num::num(void) //Defining of constructor

cout<<”Constructor 1 is called”;

num::num(int m)

cout<<”Constructor 2 is called”;

main()

num x;

num x(5);

Output:

Constructor 1 is called

Constructor 2 is called

Overloading Constructor

Like functions, it is possible to overload constructors. A class contains more than one
constructor. This is known as constructor overloading. Depending upon the arguments, the
complier executes appropriate constructor.

Constructor declaration Object declaration

(a) Num( int m,float j, char k); (a) Num x(4,4,4,’A’);

(b) Num(int m, float j); (b) Num y(1,2.2);

(c) Num(); (c) Num z;

When the object is created, the constructor with three arguments is called because
the declaration of an object is followed by three arguments. For object y, constructor with
two arguments is called and lastly object z, which is without any argument, is candidate for
constructor without argument.

COPY CONSTRUCTOR

Using copy constructor, it is possible for the programmers to declare and initialize
one object using reference of a another object. This constructor is called as copy
constructor.

Example

num( num &j)

n=j.n;

num l=j; // copy constructor is executed

Program for Copy Constructor

#include<iostream.h>

#include<conio.h>

class num

int n;

public:

num();{ } //constructor without argument

num(int k) //constructor with one argument

n=k;

num(num &j) //copy constructor

n=j.n;

void show(void)

cout<<n;

};

main()

clrscr();
num j(50);

num k(50);

numk(j);

num l=j;

num m;

m=j;

cout<<”\n object j value of n : “;

j.show();

cout<<”\n object k value of n : “;

k.show();

cout<<”\nobject l value of n:”;

l.show();

cout<<”\nobject m value of n:”;

m.show();

return 0;

Output:

object j value of n :50

object k value of n :50

object l value of n :50

object m value of n :50

DESTRUCTOR

Destructor is also a member function like constructor. It destroys the class objects
created by constructors. The destructors have the same name as their class, preceeded by a
tilde~.

Program for destructor

#include<iostream.h>

struct text

text() //constructor

cout<<”\n constructor executed.”;

~text() //destructor

cout<<”\n destructor executed.”;


}

};

void main()

clrscr();

text t; //object declaration

Output:

Constructor is executed.

Destructor is executed.

ANONYMOUS OBJECTS

Objects are created with names. It is possible to create objects without name and
such objects are known as anonymous objects. When constructor and destructors are
invoked, the data members of the class are initialized and destroyed respectively. Thus
without object we can initialize and destroy the contents of the class.
UNIT IV

OPERATOR OVERLOADING

OPERATOR OVERLOADING AND TYPE CONVERSION

The capability to relate the existing operator with a member function and use the
resulting operator with objects of its class as its operands is called operator overloading.

The keyword operator

The keyword operator defines a new action or operation to the operator.

Syntax:

return type operator operator_symbol (parameters)

Statement 1;

Statement2;

The keyword operator defines a new action or operation to the operator.

Example

number operator + ( number D)

Number T;

T.x=x+D.x;

T.y=y+D.y;

return T;

Overloaded operators are redefined within a C++ calss using the keyword operator
followed by an operator symbol. When the operator is overloaded, the produced symbol is
called the operator function name. a friend class requires one argument for unary operators
and two for binary operators.

Prototype can be return as:

void operator ++();

num operator+(num);

friend num operator * (int ,num);

Operator overloading can be carried out in the following steps:

(a) Define a class which is to be used with overeloading operations.

(b) The public declaration section of the class should contain the prototype of he
function operator().

(c) Define the definition of the operator function with proper operations for which
it is declared.
OVERLOADING UNARY OPERATORS

The operator ++,-- and – are unary operators. The unary operators ++ and –- can
be used as prefix or suffix with the functions. These operators have single operand.

Program for unary operators

#include<iostream.h>

#include<conio.h>

class num

private:

int a,b,c,d;

public:

num(int j,int k, int m,int l)

a=j;

b=k;

c=m;

d=l;

void show(void);

void operator ++();

};

void num::show()

{cout<<”a=”<<a<<”b=”<<b<<”c=”<<c<<”d=”<<d;

void num::operator ++()

++a; ++b; ++c; ++d;

main()

clrscr();

num x(3,2,5,7);

x.show();

++x;

cout<<”\n after increament of x :”;

x.show();
return 0;

Output:

Before increment of X : A=3 B=2 C=5 D=7

After increament of X : A=4 B=3 C=6 D=7

OVERLOADING BINARY OPERATORS

1. using member function

2. using friend function

Using member function

It require one argument. It contains value of a object. two objects o1,o2, the
overload function can be declared as follows,

Operator (num 02);

Num class

O2 object

The function calls operator statement as follows:

O3=o1+o2;

It can also written as o3= o1.operator +(o2);

Using friend function

The two arguments are passed as a arguments

O3=o1+o2;

O3=operator + (o1,o2);

The calling statement can be written as

X=y+3; or X=3+y;

OVERLOADING FRIEND FUNCTION

The difference between member function and friend function is that the member
function takes arguments explicitly.

Syntax:

friend returntype operator operator_symbol (var1, var2)

statement1’

Program for overloading friend function

#include<iostream.h>

class complex

float real,image;
public:

complex()

real=image=0;

complex (float r, float i) //two argument constructor

real=r;

image=i;

friend complex operator – (complex c)

c.real=-c.real;

c.imag=-c.imag;

void display()

cout<<”\n real : “<<real;

cout<<”\nimage :”<<imag;

};

void main()

clrscr();

cmplex c1(1.5, 2.5), c2;

c1.display();

c2=-c1;

cout<<”\n \n after nagation \n”;

c2.display();

Output:

Real : 1.5

Image : 2.5

After Negation

Real : -1.5

Image : -2.5
TYPE CONVERSION

There are three possibilities of data conversion as given below:

1. Conversion from basic data type to user defined data type

2. Conversion from class type to basic data type.

3. Conversion from one class type to another class type.

Conversion from basic to class type

It is automatically done by the compiler with the help of in built routines or by


applying typecasting. In this type the left hand operand of = sign is always class type and
right hand operand is always basic type.

Program for basic to class type conversion

#include<iostream.h>

class data

int x;

float y;

public:

data()

x=0;

f=0;

data (float m)

x=2;

f=m;

void show()

cout<<”\n x= “<<x<<”f=”<<f;

cout<<”\n x= “<<x<< “f=”<<f;

};

int main()

clrscr();

data z;
z=1;

z.show();

z=2.5;

z.show();

return 0;

Output:

X=2 f=1

X=2 f=1

X=2 f=2.5

X=2 f=2.5

Conversion from class type to basic data type

The complier does not have any knowledge about the user- defined data type built
using classes. In this type of conversion, the programmer explicitly needs to tell the
complier how to perform conversion from class to basic type.

Program for basic to class type conversion

#include<iostream.h>

class data

int x;

float y;

public:

data()

x=0;

f=0;

Operator int()

return(x);

Operator float()

return f;

{
x=2;

f=m;

void show()

cout<<”\n x= “<<x<<”f=”<<f;

cout<<”\n x= “<<x<< “f=”<<f;

};

int main()

clrscr();

int j;

float f;

data a;

a=5.5;

j=a;

f=a;

cout<<”Value of J= “<<j;

cout<<”Value of F=”<<f;

return 0;

Output:

Value of j=2

Value of f=5.5

Conversion from one class type to another class type

There are two ways to convert object data type from one class to another. One is to
define a conversion operator function in source class or a one argument constructor in a
destination class.

Example:

X=A;

Here X is an object of class XYZ and A is an object of class ABC. The class ABC data
type is converted to class XYZ. The conversion happens from class ABC to XYZ. The ABC is a
source class and XYZ is a destination class.
TYPES OF INHERITANCE

Single inheritance

When only one base class is used for derivation of a class and the derived class is
not used as base class.

Fig.7 – Single inheritance

Here A is a base class. B is a derived class. This type involves one base and derived
class. Further, no class is derived from B.

Example Program for single inheritance:

#include<iostream.h>

#include<conio.h>

class A

public:

int v1=10;

class B

void show()

cout<<” The value of v1=10”;

};

void main()

B obj1;

obj1.show();

Output:

The value of v1= 10

Multiple inheritance

When two or more base classes are used for derivation of a class.
A B

Fig.8 – Multiple inheritance

A and B are the base classes. C is a derived class. Class C inherits the properties of
both A and B. Further, Z is not used as a base class.

Program for multiple inheritance

#include<iostream.h>

#include<conio.h>

class a

public:

int a=10;

};

class b

public:

int b=20;

class c :: public a,b

show()

cout<<”a=”<<a<<”\n b=”<<b;

};

main()

c obj1;

obj1.show();

Output:

A= 10

B=20
Hierarchal inheritance

When a single base class is used for derived of two or more classes.

B C D

Fig.9 - Hierarchal inheritance

A is only one base class. A,B and C are derived classes. Further, B,c and D are not
used for deriving a class.

Program for Hierarchical inheritance

#include<iostream.h>

#include<conio.h>

class A

public:

int a=10,b=20,c=20;

};

class B::public A

public:

void showa()

cout<<”A=”<<a;

};

class C:: public A

public:

void showb()

cout<<”B=”<<b;

};

class D:: public A

public:
void showc()

cout<<”C=”<<c;

};

void main()

B obj1;

obj1.showa();

C obj2;

obj2.showb();

D obj3;

obj3.showc();

getch();

Output:

A=10

B=20

C=30

Multilevel inheritance

When a class is derived from another derived class. Derived class is act as a base
class for another class.

Fig.10- Multilevel inheritance

Here A is a base class. B is derived from A and C is derived from B. B is acting as a


base class as well as derived class.

Program for multilevel inheritance

#include<iostream.h>

#include<conio.h>

class A

{
public:

int a;

};

class B :: public A

public:

void get()

cin>>a;

};

class C :: public B

public:

void show()

cout<<”A=”<<a;

};

void main()

C obj1;

obj1.get();

obj1.show();

getch();

OUTPUT:

A=4

Hybrid inheritance

The combination of one or more type of inheritance


A

B C

Fig.11-Hybrid inheritance

Here A,B are the single inheritance. B,C and D are the multiple inheritance.

Program for hybrid inheritance

#include<iostream.h>

#include<conio.h>

class A

public:

int a;

};

class B :: public A

public:

void geta()

cout<<”Enter A”;

cin>>a;

};

class C

public:

int b;

void getb()

cout<<”Enter B”;

cin>>b;

};
class D :: public B,C

public:

void show()

cout<<”A=”<<a<<”\nB=”<<b;

};

void main()

D obj1;

obj1.geta();

obj1.getb();

obj1.show();

getch();

Output:

Enter A 10

Enter B 20

A= 10

B=20

Multipath inheritance

When a class is derived from two or more type of inheritance.

Fig-12 Multipath inhertance

Program for multipath inheritance

#include<iostream.h>

#include<conio.h>

class A

public:

int a,b;
};

class B: public A

public:

void geta()

cout<<”Enter A value “;

cin>>a;

};

class C : public A

public:

void getb()

cout<<”Enter b value”;

};

class D : public B,C

public:

void show()

coout<<”A=”<<a<<”\nB=”<<b;

};

void main() Output:

{ Enter a value: 10

D obj1; Enter B value : 30

obj1.geta(); A=10

obj1.getb(); B=30

obj1.show();

VIRTUAL BASE CLASSES

To overcome the duplication occurred due to Multipath inheritance, c++ provides


virtual.
Syntax

Class a1

protected :

int a;

};

class a2 : virtual public a1 //virtual class declaration

protected:

int b;

};

It avoids the duplication of member function.

Abstract classes

When a class is not used for creating objects it is called as abstract class. It act as a
base class only.
UNIT V

POINTER AND ARRAYS

POINTER

A pointer is a memory variable that stores a memory address. Pointers can have any
name that is legal for other variables and it is declared in the same fashion like other
variables but it is always denoted by * operator.

POINTER DECLARATION

Pointer variables can be declared as follows:

int *x;

float *y;

char *f;

In the first statement x is an integer pointer that holds the integer variable address.

In second statement y is an float pointer that holds float variable address.

In third statement f contains the char variable address.

#include<iostream.h>

#include<conio.h>

main()

int n;

clrscr();

cout<<”Enter a number =”;

cin>>n;

cout<<”Value of n =”<<n;

cout<<”Address of n= “ <<(unsigned)&n;

getch();

OUTPUT:

Enter a number =10

value of n=10

Address of n = 4068

POINTER TO CLASS

We can also define pointer to class. Here , starting address of the member variables
can be accessed. Such pointers are called class pointer.

Example ;

Class book

{
char name[25];

int pages;

};

class book *ptr;

The syntax for using pointer with member is given below.

Ptrname ptrpages;

POINTER TO OBJECT

Like variables, objects also have an address. A pointer can point to specified object.

Bill s;

Bill *ptr=&s;

Ptr getdata(45,1.2,12);

(*ptr).show();

The This pointer

The keyword this is a local variable that is always present in the body of any non
static member function. It does not need to be declared.

*this //it takes the local variable .

Example

#include<iostream.h>

#include<conio.h>

class num

int num;

public:

void input()

cout<<”\n Enter a number “;

cin>>num;

void show()

cout<<”\n The minimum number : “<<num;

number min(num t)

if (t.num<num)

return t;
else

return *this;

};

void main()

number n,n1,n2;

n1.input();

n2.input();

n=n1.min(n2);

n.show();

Output:

Enter a number :152

Enter a number : 234

The minimum number : 152

POINTER TO DERIVED CLASSES

It is possible to declare a pointer which points to the base class as well as the
derived class. One pointer can point to different classes. For example, X is a base class and
Y is a derived class. The pointer points to X can also point to Y.

#include<iostream.h> void main()

#include<conio.h> {

class A clrscr();

{ B *cp;

public: B b;

int b; cp=&b;

void display() cpb=100;

{ cpd=350;

cout<<”b=”<<b<<”\n”; cout<<”cp points to the derived object”;

} }; cpdisplay();

class B : public A getch();

{ }

public:

int d; Output:

void display() Cp points to the derived object

{ b=100 d=350
cout<<”b=”<<b<<

cout<<”\n”<<”d=”<<d;

In this program cp points to the objects of derived class. The pointer cp is pointer to
class B. the variable b is an object of class B. the address of b is assigned to the pointer cp.
The pointer cp can access the member variables of both base and derived classes.

ARRAYS

Array is a collection of elements of similar data types in which each element is unique
and located in separate memory locations.

ARRAY DECLARATION AND INITIALIZATION

Declaration of an array is shown below:

Declaration

int a[5];

it tells to the compiler that ‘a’ is an integer type of array and it must store five
integers. The compiler reserves two bytes of memory for each integer array element. In the
same way array of different data types are declared as below:

char ch[10];

float real[10];

long num[5];

The array initialization is done as given below:

Array initialization

int a[5]={ 2,3,4,5,6};

Here, five elements are stored in an array ‘a’. The array elements are stored
sequentially in separate locations. Reading of array elements begins from zero. Array
elements are called with array name followed by element numbers.

a[0] refers to 1st element i.e 2

a[1] refers to 2nd element i.e 3

a[2] refers to 3rd element i.e 4

a[3] refers to 4th element i.e 5

a[4] refers to 5th element i.e 6

CHARACTERISTICS OF ARRAY

1. The declaration int a[5] is nothing but creation of five variables of integer type in
memory. Instead of declaring five variables for five values, the programmer can
define them in an array.

2. All the elements of an array share the same name, and they are distinguished
from one another with the help of element number.
3. The element number in an array plays a major role in calling each element.

4. Any particular element of an array can be modified separately without


distributing other elements.

int a[5]={1,2,3,4,5};;

if the programmer needs to replace 5 with 10, he/she is not require to change all
other numbers except 5. To carry out this task the statement a[4]=10 can be
used. Here other three elements are not disturbed.

5. Any element of an array a[] can be assigned/equated to another ordinary


variable or array variable of its type.

Example :

B=a[2];

a[2]=a[3];

a) In the statement b=a[2] or vice versa, value of a[2] is assigned to b,


where b is an integer.

b) In the statement a[2]=a[3] or vice versa, value of a[2] is assigned to


a[3], where both the elements are of the same array.

6. The array elements are stored in continuous memory locations. The amount of
storage require for holding elements of the array depends upon its type size. The
total size in bytes for a single dimensional array is computed as shown below;

Total bytes = sizeof(data type)*size of array

C++ AND MEMORY

Before compiling and linking the source code, we need to specify the appropriate
memory model. Using memory models, we can set the size limits of the data and code.

Tiny

 All four segment registers(CS,DS,ES,SS) are initialized with same address


and all addressing is accomplished using 16 bits.

 Total memory capacity 64 KB

 Programs are executed quickly.

Small

 All code should fit in a single 64 KB segment and all data should fit in a 64 KB
segment.

 Pointers are 16 bits in length.

 Execution speed is same as tiny model.

 Average size programs are using this model.

Medium

All data should fit in 64 KB segment.

It uses multiple segments.

All pointers to data are 16 bits, but all jumps and calls require 32 bits addresses.
Access data is fast but slower program execution.

It is suitable for big programs.

Dynamic (Late) binding

Dynamic binding of member functions in c++ can be done using the keyword virtual.
The member function followed by the virtual keyword is called virtual function.

Program for Late binding

Class first //base class

int d;

public:

virtual void display() { } // base class member function

};

class second:public first // derived class

int k;

public:

virtual void display() { } //member function of derived class

In this example, base and derived classes have the same member function display ()
preceded by the keyword virtual. The various forms of virtual function in base and derived
classes are dynamic bounded. The references are detected from the base class.

The functions can invokes as follows

s.first::display(); // Invokes base class function

s.display(); // Invokes derived class function

Here s is an object, first is an base class.

VIRTUAL FUNCTION

Virtual function of base classes must be redefined in the derived classes. The
programmer can use the same function name in any derived class, even if the number and
type of arguments are matching. The function overrides the base class function of the same
name. virtual functions can only be member functions. We can also declare the functions as
given below:

int base :: get(int) and int derived :: get(int) even when they are not virtual.

In virtual function if two functions with the same name have different arguments,
C++ complier them as different, and the virtual mechanism is dropped.

#include<iostream.h>

#include<conio.h>

class first

{
int b;

public:

first() { b=10};

virtual void display()

cout<<”\n b=”<<b;

}};

class second : public first

int d;

public:

second(){ d=20;}

void display()

cout<<”\n d= ”<<d;

};

int main()

clrscr();

first f,*p;

second s;

p=&f;

pdisplay();

p=&s;

pdisplay();

return 0;

Output :

b=10

d=20
APPLICATIONS WITH FILES

FILE:

The file is an accumulation of data stored on the disk created by the user. The
programmer assigns file name. The file name are unique and are used to identify the file.
No two files can have the same name In the same directory. There are various types of files
such as text files, program files, data files, execution files etc.

Data files contain a combination of numbers, alphabets, symbols etc. called data.

Data communication can be performed between program and output devices or files
and program. File streams are used to carry the communication among all devices. The
stream is nothing but flow of data in bytes in sequence. If data were received from
input devices in sequence then it is called as source stream. When the data were received
from input devices then it is called as destination stream.

FILE STREAM CLASSES

Stream is nothing but flow of data. In object programming the streams are
controlled using the classes. The operations with the files are mainly two types. There are,
read and write.

ios is a base class. All other classes are derived from the ios class. These classes
contain several member functions that perform input and output operations. The streambuf
class has low level routines for controlling data buffer.

The streambuf and ostream classes control input and output functions respectively.
The ios is the base class of these two classes. The member function of these classes handle
formatted and unformatted operations. The functions get(), getline(), read() and overloaded
extraction operatord(>>) are defined in the istream class. The function put(), write() and
overloaded insertion operation operators (<<) are defined in the ostream class.

The iostream class is also a derived class. It is derived from istream and ostream
classes. There are also a derived classes. It is derived from istream and ostream classes.
There are also another three useful derived classes. They are istream_withassign,
ostream_withassign and ostream_withassign. They are derived from istream,otream, and
fstream classes.

The fileBuf accomplishes input and output operations with files. The streambuf class
does not organize streams for iput or output operations. The derived classes of streambuf
perform these operations. It also arranges a space for keeping input data and for sending
output. The I/O functions of classes istream and ostream invoke the filebuf functions to
perform the insertion or extraction on the streams.

The FSTREAMBASE acts as a base class for fstream, ifstream and ostream. The
functions such as open() and close() are defined in fstreambase.

The IFSTREAM is a derived class from fstreambase and istream by multiple


inheritance. It can access the member functions such as get(),getline(),seekg(), tellg() and
read(). It allows input operations and provides open() function with default input mode.

The OFSTREAM class derived from fstreambase and ostream classes. It can access
the member functions such as put(), seekg(), write() and tellp(). It allows output operations
and provides member function open() with output mode.
The FSTREAM allows simultaneous input and output operations on a filebuf. The
member functions of base classes istream and ostream start the input and output.

SEQUENTIAL READ AND WRITE OPERATIONS

C++ allows file manipulation command to access file sequentially or randomly. The
data of sequential file must be accessed sequentially i.e, oe character at a time. In order to
access nth number of bytes, all previous characters are read and ignored. There are number
of functions to perform read and write operations with files. Some function read/write single
character and some function read/write block of binary data. The put() and get() functions
are used to read or write a single character whereas write() and read() are used to read or
write block of binary data.

The put() and get() function

The function get() is a member function of the class fstream. This function reads a
single character from the file pointed by the get pointer.

The put() function writes a character to the specified file by the stream object. it is
also a member of fstream class. The put() function places a character in the file indicated by
put pointer.

#include<iostream.h> While(1[text]!=’\o’)

#include<conio.h> Io.put(text[1++]);

#include<string.h> Io.seekg(0);

int main() { char c;

clrscr(); cout<<”\n Enter text :”;

char text[50]; while(io){

cout<<”\n Enter a text :”; io.get(c);

cin.getline(text,50); cout<<c;

int i=0; }

fstream io; return 0; }

io.open(“data”,ios::in|ios::out); Enter a text : Kumaran

Entered text : Kumaran

In this program file data is opened in read and write mode. The getline() function
used to read the string and it stores in the array text[50]. The statement io.put(text[i++])
reads ted data and writes in the screen.

BINARY AND ASCII FILES

The insertion and extraction operators known as stream operator handles formatted
data. The programmer needs to format data in order to represent it in a suitable fashion.
ASCII codes are used by the I/O devices to share or pass data to share or pass to the
computer system. But central processing unit manipulates the data using binary numbers 0
and 1. for this reason, it is essential to convert the data while accepting data from input
devices and displaying the data on output devices.
cout<<k; //displaying value of k on screen

cin>>k; // reads value for k from keyboard

here, k is an integer variable. The operator << converts value of integer variable k
into stream of ASCII character. In the same fashion, the << operator converts the ASCII
characters entered by the user to binary. The data is entered through the keyboard,
standard input devices. For example, we entered 2 the stream operator >> gets ASCII
codes of the individual digits of the entered number 2. The stream operator << converts the
value of k that is stored in binary format into equivalent ASCII codes.

#include<fstream.h>

#include<constream.h>

int main()

clrscr();

char c;

ifstream in(“dat”);

if(!in)

cerr<<”Error in opening file. “;

return 1;

while(in.eof()==0)

cout<<(char)in.get();

return 0;

In this program the data file is opened in read mode. The file already exists. Using
get() member of ifstream class, the contents of file is read an displayed.

The write() and read() function

The data entered by the user are represented in ASCII format. However, the
computer can understand only machine formats 0 and 1. when data is stored in text format
numbers are stored as characters and occupy more memory space. The limitations can be
overcome using write() and read() functions. The write() and read() functions. The write()
and read() functions use binary format of data during operations. The data representation is
same in file and system. The bytes required to store an integer in text form depends upon
its size where as in binary format the size is fixed. The binary form is exact and allows quick
read and write operation because no conversion takes place during operations. The formats
of the write() and read() functions are given below:

in. read((char*) &p,sizeof(p);


out. write((char*) &p,sizeof(p);

Reading and writing class objects

The functions read() and write() perform write and read() operations in binary
format that is exactly same as internal representation of data in the computer. Due to
these capabilities of the functions, large data can be stored in small amount of memory.
Both these functions are also used to write and read operation only data members are
written to the file and the member functions are ignored.

RANDOM ACCESS MEMORY

Data files always contain large information and the information always changes. The
changed information should be updated otherwise the data files are not useful. Thus to
update data in the file we need to update the data files with latest information. To update
the data files with latest information. To update a particular record of data file it may be
stored anywhere in the file it is necessary to obtain at which location the data object is
stored.

The sizeof() operator determines the size of object. consider the following
statements.

int size=sizeof(o);

where o is an object and size is an integer variable. The sizeof() operator returns the
size of object o in bytes and it is stored in the variable size. Here, one object is equal to one
record.

The position of nth record or object can be obtained using the following statements.

int p=(n-1 * size);

Here p is the exact byte number of the number of the object that is to be updated, n
is the number of object, and size is the size in bytes of an individual object.

Suppose we want to update 5 th record. The size of individual object is 26.

P=(5-1*26) i.e, p=104 thus the fifth object is stored in a series of bytes from 105 to
130.

TEMPLATES

A function that works for all c++ data types is called as templates. Templates help
the programmers to declare group of functions or classes.

Need of template

Template is a technique that allows using a single function that can process any
type of data types. Using template we can create a single function that can process any
type of data. The formal arguments of template functions are of template type. They can
accept data of any such as int, float, long etc. thus, a single function can be used to accept
values of different datatypes.

Definition of class template

To declare a class of template type following syntax is used.

Template declaration

template class <T>


class name_of_class

//class data member and function

The first statement template class<T> tells the complier that the following class
declaration can use the template data type. T is a variable of template type that can be
used in the class to define variable of template type. Both template and class are keywords.
The <> is used to declare variables of template type that can be used inside the class to
define variables of template type. One or more variables can be declared separated by
comma. Templates cannot be declared inside class or functions. They must global and
should not be local.

T K;

Where k is the type of type template. Most of the authors use T for defining template
instead of T, we can use any alphabet.

Program for template

#include<iostream.h>

#include<conio.h>

template <class T>

class data

public:

data (T c)

cout<<”\n”<<”c=”<<c<<” size in bytes: “<<sizeof©;

}};

int main()

clrscr();

data <char> h(‘A’);

data <int> i(100);

data <float> j(3.12);

return 0;

output :

c=a size in bytes: 1

c=100 size in bytes: 2

c=3.12 size in bytes: 4


NORMAL FUNCTION TEMPLATES

The declaration of template normal function can be done as follows.

Template class<T>

Function_name()

//code

Example:

void show (T X)

cout<<”\n x=”<<x;

show(c);

show(i);

show(d);

here x is template argument. Show is a normal function.

TEMPLATES WITH MORE PARAMETERS

Like functions classes can be declared to handle different data types. The class
contains more than one argument. The arguments are separated by comma with template
declaration. The declaration is as follows:

Template with multiple arguments

template <class T1, class T2>

class name_of_class

// class declaration and definitions

Example:

#include<iostream.h>

#include<conio.h>

template <class T1, class T2>

class data

public:

data(T1 a, T2 b)
{

cout<<a<<b;

}};

void main()

clrscr();

data <int,float> h(2,2.5);

data <int ,char> i(15,’c’);

getch();

Output :

2 2.5

15 c

In this program, the constructor has two parameters of template type. Consider
data<int, float> h(2,2.5). the compiler tells that first argument is of integer type and
second argument is of float type.

Function with more arguments

Syntax:

template <class T>

return_type function_name (parameter of template type)

statements;

Program for template with more arguments

#include<iostream.h>

#include<conio.h>

template<class A, class B, class C>

void show( A c, B I, C f)

cout<<”\n c=”<<c<<”i=”<<i<<”f=”<<f;

int main()

clrscr();

show(‘A’,8,50.25);

show(7,’B’,70.89);
return 0;

Output:

C=A i=8 f=50.25

C=7 i=8 f=70.89

Exception handling

The errors may be logical errors or syntactic error. The logical errors remain in the
program due to poor understanding of the program. The syntax mistakes are due to lack of
understanding of programming language. C++ provides exception handling procedure due
to reduce the errors that a programmer makes.

Principles of exception handling

Exceptions are two types,

There are,

1. Synchronous exceptions

2. Asynchronous exceptions

C++ has a well organized object oriented method to control run time errors that
occur in the program. The goal of exception handling is to create a routine that detects and
sends an exceptional condition in order to execute suitable action

The routine needs to carry following responsibilities

1. Detect the problem

2. Warn that an error has come

3. Accept the error message

4. Perform accurate actions without troubling the user.

The Keywords try, throw and catch

The try keyword is followed by a series of statements enclosed in curly braces.

Syntax for try

try

statement 1;

statement 2;

Syntax for throw

throw (excep);

throw excep;

throw;

Syntax for Catch

try
{

statement 1;

statement 2;

catch (argument)

statement 3; //Action to be taken

try block

Finds errors and throws or executes an exceptions

throw block

Throws exception

Catch block

Gathers exceptions from try block

Fig.13- Exception handling mechanism

EXCEPTION HANDLING MECHANISM

C++ exception handling mechanism provides three keywords: try, throw and catch.
the keyword try used at the starting of exception. The throw block is present inside the try
block. Immediately after try block, catch () block is present.

As soon as exception is found, the throw statement inside the try block throws an exception
for catch() block that an error has occurred in the try block throws an exception occurring
inside the try block are used to throw exception. the catch receives the exceptin send by the
throw block.

Statement 1;

Statement 2;

try //beginning of exception handling routine

Statement;

Statement;

throw(object); //Statements that finds and forces to throw an


exception

catch(object) //Traps Exception


{

Statement;

Statement;

Statement; //Statement that controls exception

Statement;

} //End of exception handling routine

WORKING WITH STRINGS

A string is nothing but sequence of characters. The string can contain small and
capital letters, numbers and symbols. String is an array of character type. Each element of
string occupies a byte in the memory. Every string is terminated by a null character.

The followings are the string library functions,

Functions Description

strlen() Determines length of a string

strcpy() Copies a string from source to destination

strcmp() Compares characters of two strings

strlwr() Converts upper case to lower case

strupr() Converts lower case to upper case

strdup() Makes duplicates string

strcat() Appends source string to destination string

strrev() Reverse the string

Table.9- String library functions

Example for string function

#include<iostream.h>

#include<conio.h>

#include<string.h>

int main()

char name[15];

clrscr();

cout<<”\nEnter your name: “;

cin>>name;

cout<<”\n Length of string is “<<strlen(name);

return 0;

}
Output:

Enter your name : saranya

Length of string is : 7

You might also like