You are on page 1of 138

SEMESTER IV

CORE VIII - OBJECT ORIENTED PROGRAMMING WITH C++


UNIT – I
Object-Oriented Programming: Principles – Benefits of OOP – Application of OOP – Tokens,
Expression and Control Structures: Tokens – Keywords – Identifiers and Constants – Data types –
Constants – Variables – Operators – Manipulators – Expressions – Control Structure.
UNIT – II
Functions – Prototyping – Call by Reference – Return by Reference – Inline Functions – Default
Arguments – const Arguments – Function Overloading – Friend and Virtual Functions, Classes and
Objects – Class – Member Functions – Arrays with in a Class – Memory Allocation for Objects – Static
data members – Static member functions – Arrays of Objects – Objects as Function Arguments –
Friendly Functions – Returning Objects – const Member Functions – Pointers to Members, Constructors
and Destructors.
UNIT – III
Operator Overloading and Type Conversions, Inheritance: Extending Classes – Derived Classes – Single
Inheritance – Multilevel Inheritance – Multiple Inheritance – Hierarchical Inheritance – Hybrid
Inheritance – Virtual Base Classes – Abstract Classes, Pointers, Virtual Functions and Polymorphism.
Pointers: Pointers to Objects –this Pointer – Pointers to Derived Classes – Virtual Functions – Pure
Virtual Functions
UNIT – IV
Managing I/O Operations: C++ Streams – C++ Stream Classes – Unformatted I/O and Formatted I/O
Operations – Managing Output with Manipulators, Working with Files - Classes for File Stream
Operations – Opening and Closing a File – Detecting end-of-file – File Pointers and their Manipulators –
Sequential I/O Operations – Updating a File – Error Handling during File Operations – Command Line
Arguments
UNIT – V
Templates: Class Templates – Class Templates with Multiple Parameters – Function Templates –
Function Templates with Multiple Parameters – Overloading of Template Functions – Member Function
Templates – Non-Type Template Arguments, Exception Handling: Basics - Exception Handling
Mechanism – Throwing Mechanism – Catching Mechanism – Rethrowing an Exception – Specifying
Exceptions

1
PRINCIPLES OF OOP
Now, let us discuss some of the main features of Object Oriented Programming which you will be using in
C++(technically).

1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various
member functions to perform tasks.
Class
It is similar to structures in C language. Class can also be defined as user defined data type but it also
contains functions in it. So, class is basically a blueprint for object. It declare & defines what data variables
the object will have and what operations can be performed on the class's object.
Abstraction
Abstraction refers to showing only the essential features of the application and hiding the details. In C++,
classes can provide methods to the outside world to access & use the data variables, keeping the variables
hidden from direct access, or classes can even declare everything accessible to everyone, or maybe just to
the classes inheriting it. This can be done using access specifiers.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and functions together
in class.
Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is called
the Base class & the class which inherits is called the Derived class. They are also called parent and child
class.
So when, a derived class inherits a base class, the derived class can use all the functions which are defined in
base class, hence making code reusable.
Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will perform
different actions. That means, functions with same name, but functioning in different ways. Or, it also allows
us to redefine a function to provide it with a completely new definition. You will learn how to do this in
details soon in coming lessons.
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.

2
Benefits of OOP
1. Data Re-usability:- “Write a once and use multiple time” we can achieve this by using class.
Once We Write a class we can bus it number of time by creating the object for class.
2. Data Redundancy:- Inheritance is the good feature for data redundancy if you need a same
functionality in multiple class you can write a common class for the same functionality and inherit
that class to sub class.
3. Easy Maintenance:- It is easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
4. Data hiding:- Implementation details are hidden from other modules and other modules has a
clearly defined interface.
5. Security:- Using data hiding and abstraction we are providing necessary data only it mean we are
maintaining security.
6. Modularity:- Programs are not disposable. Legacy code must be dealt with on a daily basis, either
to be improved upon (for a new version of an exist piece of software) or made to work with newer
computers and software. An Object Oriented Program is much easier to modify and maintain than
a non-Object Oriented Program. So although a lot of work is spent before the program is written,
less work is needed to maintain it over time.

Applications of OOP

 User interface design such as windows, menu.


 Real Time Systems
 Simulation and Modeling
 Object oriented databases
 AI and Expert System
 Neural Networks and parallel programming
 Decision support and office automation systems etc.

3
Characteristics of C++
C++ is not a purely object-oriented language but a hybrid that contains the functionality of the C
programming language.
This means that you have all the features that are available in C:
■ universally usable modular programs
■ efficient, close to the machine programming
■ portable programs for various platforms.

Screen output :

Enjoy yourself with C++!

4
The first line begins with the number symbol, #, which indicates that the line is intended for the pre-
processor.

This allows the program access to all the information contained in the header file. The header file iostream
comprises conventions for input and output streams. The word stream indicates that the information involved
will be treated as a flow of data.

Program execution begins with the first instruction in function main(), and this is why each C++ program
must have a main function. Apart from the fact that the name cannot be changed, this function’s structure is
the same as of any other C++ function.

Usually the main() function contains two statements. The first statement

cout << "Enjoy yourself with C++!" << endl;

outputs the text string “ Enjoy yourself with C++!” on the screen. The name cout (console output) designates
an object responsible for output. The two less-than symbols, << (left-shift operator) indicate that characters
are being “pushed” to the output stream. Finally endl (end of line) causes a new line feed.

5
Structure of Simple C++ Program
//DOCUMNETATION SECTION

/* This is a structure of simple C++ program*/

//LINKING SECTION

#include <header file(s)> //Pre-Processor with linked header file

//DEFINITION SECTION

#define const value //Definition of symbolic constants

//GLOBAL DECLARATION SECTION


datatype variable_name value //Declaration of global variables

returntype function_name(formal_parameters); //Proto-type Declaration of user defined functions

//CLASS DECLARATION SECTION


class class_name
{
access_specifier:data_members;
access_specifier:member_functions;
};

//MAIN FUNCTION
returntype main(arguements)
{
statement(s);
} //Definition of the main function

//OBJECT DECLARATION SECTION


class_name object_name;

//SUB-PROGRAM SECTION
/*In this section the user-defined functions are defined */

BASIC DATA TYPES

6
DATA TYPES RANGE

TYPE SIZE RANGE (decimal)


char 1 byte -128 to +127 / 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to +127
int 2 byte -32768 to +32767
unsigned int 2 byte 0 to 65535
short 2 byte -32768 to +32767
unsigned short 2 byte 0 to 65535
long 4 byte -2147483648 to +2147483647
unsigned long 4 byte 0 to 4294967295
-3.4E+38 (up to 6 digits
float 4 bytes
accuracy)
-1.7E+308 (up to 15digits
double 8 bytes
accuracy)
-1.1E+4932 (up to 19 digits
long double 10 bytes
accuracy)

Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the
data-type with which it is declared. Every data type requires different amount of memory.
Data types in C++ is mainly divided into two types:
1. Primitive Data Types: These data types are built-in or predefined data types and can be used directly
by the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C+
+ are:

 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

2. Abstract or user defined data type: These data types are defined by user itself. Like, defining a class
in C++ or a structure.
Let us discuss about  primitive data types available in C++.
 Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory
space and ranges from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. Keyword used for character data type
is char. Characters typically requires 1 byte of memory space and ranges from -128 to 127 or 0 to 255.
 Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can store
either true or false. Keyword used for boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single precision floating point values or
decimal values. Keyword used for floating point data type is float. Float variables typically requires 4
byte of memory space.
 Double Floating Point: Double Floating Point data type is used for storing double precision floating
point values or decimal values. Keyword used for double floating point data type is double. Double
variables typically requires 8 byte of memory space.
 void: Void means without any value. void datatype represents a valueless entity. Void data type is used
for those function which does not returns a value.

7
 Wide Character: Wide character data type is also a character data type but this data type has size
greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long.

CONSTANTS (LITERALS)

The signed and unsigned Modifiers

The short, int, and long types are normally interpreted as signed with the highest bit representing the sign.
However, integral types can be preceded by the keyword unsigned. The amount of memory required remains
unaltered but the range of values changes due to the highest bit no longer being required as a sign. The
keyword unsigned can be used as an abbreviation for unsigned int.

The char type is also normally interpreted as signed. Since this is merely a convention and not mandatory,
the signed keyword is available.
Thus three types are available: char, signed char, and unsigned char.

The sizeof Operator


The amount of memory needed to store an object of a certain type can be ascertained using the sizeof
operator: sizeof(name)
yields the size of an object in bytes, and the parameter name indicates the object type or the object itself. For
example, sizeof(int)represents a value of 2 or 4 depending on the machine. In contrast, sizeof(float) will
always equal 4.

8
ESCAPE SEQUENCES

KEYWORDS

9
RULES FOR NAMING AN IDENTIFIER
■ a name contains a series of letters, numbers, or underscore characters ( _ ). German umlauts and
accented letters are invalid. C++ is case sensitive; that is, upper- and lowercase letters are
different.
■ the first character must be a letter or underscore
■ there are no restrictions on the length of a name and all the characters in the name are significant
■ C++ keywords are reserved and cannot be used as names.

COMMON CONVENTIONS
Conventions In C++ it is standard practice to use small letters for the names of variables and functions. The
names of some variables tend to be associated with a specific use.

EXAMPLES:
c, ch for characters
i, j, k, l, m, n for integers, in particular indices
x, y, z for floating-point numbers

DECISION MAKING STATEMENT (OR) CONTROL STATEMENT:

The control statements are used to make a decision several control statement available in c.
1. If statement.
2. If else statement.
3. Nested if statement.
4. Else if ladder.
5. Switch statement.
6. Goto statement.
1. Simple if statement:
Simple if is a one-way branching statement .when the condition of if is true, the statement
present within the if block are executed, otherwise the if block is skipped by transferring the
control directly to the first statement after the if block
Syntax:
If(condition)
{
statement;
}
Flowchart:

If
true
conditio
n
statement
False

exit

10
Example:
# include<iostream.h>
void main()
{
int a;
cin>>a;
if(a>20)
cout<<”Greater than 20”;
}
Output:
30
Greater than 20

Description:
The above program as illustrated for using simple if statement. If the user enter the a
value is greater than 20. Then the “greater than 20” statement will be printed otherwise if
block is skipped by transferring the control directly to the first statement after if block.

2. If ..else statement
 If …else statement is two way branching statement.
 If the condition is true ,then the statement present within the if block are executed,
otherwise the else block are executed.

Syntax:
if(condition)
{
True_block statement
}
else
{
False_block statement
}

Flow chart:
Entry

True If false
conditio
n

True block statement False block statement

Next statement

11
Example program:
#include<iostream.h>
void main()
{
int n;
cin>>n;
if(n%2= =0)
cout<<”even number”;
else
cout<<“odd number”;
}

Output:
8
Even number

Description:
The above program is illustrated for the use of if else statement, if(n%2= =0) the condition is
true the given number is even otherwise false the given number is odd should be printed.

3. Nested –if statement


 A structure consisting of an if statement within another if statement is called nested if
statement.
 If the condition-1 false the statement-3 will be executed, otherwise it contains to
perform the second text.
 If condition 2 is true statement-1 is will be evaluated, otherwise the statement-2 will
be evaluated.

Syntax:
If (condition)
{
If(condition-2)
{
Statement-1
}
else
{
Statement-2
}
}
else
{
Statement-3
}
Statement-x;

12
Flowchart:
entry

False true
Co
n-

False C true
o

statement-3
Statement-2 Statement-1

Statement-x

Example program:
#include<iostream.h>
void main()
{
int a,b,c;
cout<<a<<b<<c);
if(a>b)
{
if(a>c)
{
cout<<”largest”<<a;
}
else
{
cout<<”largest”<<c;
}
}
else

{
if(c>b)
{
cout<<”largest”<<c;
}
else
{
cout<<” largest”<<b;
}
}
}

Output:
10 20 5

13
20 largest

Description:
The above program as illustrated the use of nested if statement. hear the first condition (a>b)
is true then it will enter to the second condition (a>c) otherwise it will entered for the third
condition(c>b). if the second condition is true the a is largest will be printed otherwise false c largest
will be printed , if the third condition is true c largest will be printed otherwise false means b largest
will be printed.

4. Else…if Ladder
The else-if ladder is a multiday decision maker which contains two or more else if ,from any
one block is executed.

Syntax:
if(condition-1)
Statement-1
elseif (condition-2)
Statement-2;
elseif (condition-3)
Statement-3;
------------------

--------------------
elseif (condition-n)
Statement-n;
else
Default statement
Statement-x;

Flowchart:

14
Example program:
#include<iostream.h>
void main()
{
float per;
cin>>per;
if(per>=75)
cout<<”distinction”;
elseif (per>=60)
cout<<“first class”;
elseif(per>=50)
cout<<“second class”;
elseif(per>=40)
cout<<“third class”;
else
cout<<“fail”;
}
Output:
56
First class
Description:
The above program is illustrated the use of else if ladder structure. If the first condition
(per>=75) is true then distinction will be printed otherwise false means the second condition (per>=60)
will be checked if its true first class will be printed otherwise it will enter to third condition (per>=50) if
its true second class will be printed, otherwise false means it will entered the last condition (per>=40) if
its true means third class will be printed otherwise false means fail will be printed.

5. Switch case statement


 The switch statement provides multi-way branching.
 The switch allows the user to select any one of the alternatives depending on the value
of an expression.
 The expression present within a parenthesis of switch statement must be of the type
int (or) char
Syntax:
switch(expression)
{
case label 1: statement 1;
break;
case label 2: statement 2;
break:
--------------------------------
--------------------------------
case label n: statement n;
break;
default : default statement;
}
statement x
 If the expression value is same as case label, then the statement corresponding to that
particulars case is executed.
 In case the expression value does not match with any case label, the statement in the
default block will be executed.

15
Flowchart:

Switch
expressi

Statement 1 Statement 2 statementn

Next statement

Example program:
#include<iostream.h>
void main()
{
int ch;
cin>>ch;
switch(ch)
{
case 1: cout<<“Sunday”;
break;
case 2: cout<<“Monday”;
break;
case 3: cout<<“tuesday”;
break;
case 4: cout<<“wednesday”;
break;
case 5: cout<<“thursday”;
break;
case 6: cout<<“friday”;
break;
case 7: cout<<“Saturday”;
break;
default: cout<<“invalid”;
}
}
Output:
4
Wednesday
Description:
The above program is illustrated for using switch case statement. If the user enter the choice
through the variable ‘ch’. If it match the case1 to case 7 the required statement will be printed
otherwise default statement invalid is printed at run time.

6. Goto statement

16
Go to statement transfer control unconditionally to another part of the program which is
marked by a label.

Syntax:
Goto label;
A lable is a valid name of variable.
Goto label;
-------------
-------------
label: statement;

Example program:
#include<iostream.h>
void main()
{
int x;
cin>>x;
if(x%2==0)
Goto even;
else
goto odd;
even:cout<<“even number”;
odd:cout<<“odd number”;
}

Output:
5
Odd number

Description
The above program is illustrated the use of goto statement. When if the condition (x%2== 0)
if matchs to true the label even statement will be printed otherwise false means label odd statement
will be printed.

DECISION MAKING AND LOOPING

Looping:
A sequence of statement is executed until some condition for termination of the loop are satisfied. It
consists of two segments.
1. Body of the loop
2. Control statement
Classification of control structure
1. Entry controlled loop/pre test
2. Exit controlled loop/post test
1. Entry controlled loop:
The control condition is tested before the start of the loop execution. If the condition are not
satisfied, then the body of the loop will not be executed.
2. Exit controlled loop:
The test is performed at the end of the body of the loop and the body of the loop is executed
unconditionally for the first time.
1. While statement:
While is an entry controlled loop statement. If is used to execute the statements repeated as long as
the condition is true.

17
Syntax:
While (condition)
{
Body of the loop;
}

Flowchart:

 The test condition is evaluated and if the condition is true ,then the body of loop is executed.
 After execution of the body, the test condition is once again evaluated and if it is true ,the boy is
executed once again.
 If the condition is false then the control is transferred out of the loop.

Example:
#include<iostream.h>
void main()
{
int n,i=0;
int s=0;
cin>>n;
while (i<=n)
{
s =s+i:
i =i+1;
}
cout<<“%d”,s;
}

Output:
5
15

Description:
The above program is the use of wile statement when for user may entered n value is 5, then the
condition (i<=n) must be checked repeat up to that the s value will be calculated s=s+i and I value also

18
increase for the body of the loop when the condition is false immediately the final calculation value of s will
be printed in the screen.
2.Do-while statement:
 Do-while is an enit controlled loop it is used to test the condition after executing the body of the
loop for first time.
 if is condition is true ,again the body of the loop will be executed .
 if the condition is false , then the control transferred out of the do-while .

Syntax:
do
{
Body of the loop;
}
while(test –condition);

Flowchart:

The test condition is evaluated at the bottom of the loop is called exit controlled loop.

Example:
#include<iostream.h>
void main()
{
int i=0,s=0,n;
cin>>n;
do
{
s=s*I;
i=i+1;
}
while(i<=n);
cout<<“%d”,s;
}
cout<<“%d”,s;
}

Output:
5
120
Description:
The above program is illustrated the use of do-while statement .when the user entered the n value is
5,it will calculated s=s+I and i=i+1 upto the condition (i<=n) false onwards , if reached false then the
process will be stopped , then the output s value 120 will be printed in the screen.

3. For statement :

19
For statement is an entry controlled looping statement .it is used to execute the statement for a
certain number of times.

Syntax:
For (initialization; test condition; increment /decrement)
{
Body of the loop;
}

Flow chart:

1. Initialization of control variables is done first


2. The value of the control variable is tested using the test condition test condition relational
expression .if the condition is the body of the loop is executed , otherwise loop is terminated
3. When the body of the loop is executed ,he control is transferred back to the for statement
after evaluating the last statement in the control variable incremented .

Example :
• for (i=0;i<10;i++)
{
cout<<i;
}

• for (i=0;i>=0;i--)
{
cout<<i;
}

Example program:
#include<iostream.h>
void main()
{
int i,n,s=0;
cin>>n;
for (i=0; i<=n;i++)
{
s=s+i;
}
cout<<“%d”,s;
}

Output:
5
15

20
Description :
The above program is illustrated the use of for statement , when the user enter the n value is 5, then the
condition checked first I<=n upto ,if it’s true the body loop statement s=s+i is calculated the I value is
increased simultaneously i++. Finally if the condition reach false then output s value 15 will be printed.

Additional features:
1. More then one variable can be initialized at time using separator comma.
Ex.
For (p=1,n=0;n<10;++n)
2. The initialization section ,increment /decrement section may also have more then one part .
Ex.
for (n=1,m=50;n<=m;n=n+i; m=m-1)
{
p=m/n;
cout<<n<<m<<p;
}
3. The test condition may have any compound relation the loop uses a compound test condition
Ex.
s=0;
for (i=1;i<20&&s<100;++i)
{
s=s+i;
cout<<i<<s;
}
4. For loop is also permissible to use expressions in the assignment statement of initialization
and increment /decrement sections.
Ex.
for x=(m+n)/2;x>0;x=x/2)

5. for loop is that one or more section can be omitted .


m=5;
for (;m!=10;)
{
cout<<m;
m=m+5;
}

Nesting of for loop:


One for statement within another for statement is called nested for loop.
Ex.
for (m=1;,m<=n;m++)
for (n=1;n<=n;n++)
{
j=m*n;
cout<<j;
}

21
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C++ is rich in built-in operators and provide the following types of operators −

Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by
one.

Arithmetic Operators
There are following arithmetic operators supported by C++ language

Operator Description

+ Adds two operands

- Subtracts second operand from the first

* Multiplies both operands

/ Divides numerator by de-numerator

% Modulus Operator and remainder of after an integer division

++ Increment operator, increases integer value by one

-- Decrement operator, decreases integer value by one

Relational Operators
There are following relational operators supported by C++ language

Operator Description

== Checks if the values of two operands are equal or not, if yes then condition becomes true.

!= Checks if the values of two operands are equal or not.

22
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition
becomes true.

>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes
then condition becomes true.

<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then
condition becomes true.

Logical Operators
There are following logical operators supported by C++ language.

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then condition (A && B) is
becomes true. false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is


condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. !(A && B) is
If a condition is true, then Logical NOT operator will make false. true.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as
follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

23
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000
the result if it exists in both operands. 1100

| Binary OR Operator copies a bit if it (A | B) will give 61 which is 0011


exists in either operand. 1101

^ Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011
it is set in one operand but not both. 0001

~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100
unary and has the effect of 'flipping' 0011 in 2's complement form due to a
bits. signed binary number.

<< Binary Left Shift Operator. The left


operands value is moved left by the A << 2 will give 240 which is 1111
number of bits specified by the right 0000
operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 will give 15 which is 0000
number of bits specified by the right 1111
operand.

24
Assignment Operators
There are following assignment operators supported by C++ language

Operator Description Example

= Simple assignment operator, Assigns values from right side C = A + B will assign
operands to left side operand. value of A + B into C

+= Add AND assignment operator, It adds right operand to the left C += A is equivalent to C
operand and assign the result to left operand. =C+A

-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C =


from the left operand and assign the result to left operand. C-A

*= Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C


with the left operand and assign the result to left operand. =C*A

/= Divide AND assignment operator, It divides left operand with the C /= A is equivalent to C =
right operand and assign the result to left operand. C/A

%= Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to C


operands and assign the result to left operand. =C%A

<<= Left shift AND assignment operator. C <<= 2 is same as C = C


<< 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C


>> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C


&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^


2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

25
Misc Operators
The following table lists some other operators that C++ supports.

Sr.No Operator & Description

1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.

2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X
otherwise returns value of Y.

3 ,
Comma operator causes a sequence of operations to be performed. The value of
the entire comma expression is the value of the last expression of the comma-
separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes,
structures, and unions.

5 Cast
Casting operators convert one data type to another. For example, int(2.2000)
would return 2.

6 &
Pointer operator & returns the address of a variable. For example &a; will give
actual address of the variable.

7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.

Operators Precedence in C++


Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator –

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

26
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

OTHER IMPORTANT OPERATORS

27
SEPARATORS

28
UNIT II

FUNCTIONS

DECALRING FUNCTIONS
A function has a name and a type, much like a variable. The function’s type is defined by its return value,
that is, the value the function passes back to the program. In addition, the type of arguments required by a
function is important. When a function is declared, the compiler must therefore be provided with information
on
■ the name and type of the function and
■ the type of each argument.
This is usually referred to as the function prototype.

The prototype above yields the following information to the compiler:


■ func is the function name
■ the function is called with two arguments: the first argument is of type int, the second of type double
■ the return value of the function is of type long.

UNDERSTANDING AND USING HEADER FILES


Header files are text files containing declarations and macros. By using an #include directive these
declarations and macros can be made available to any other source file, even in other header files.
Pay attention to the following points when using header files:
■ header files should generally be included at the start of a program before any other declarations
■ you can only name one header file per #include directive
■ the file name must be enclosed in angled brackets < ... > or double quotes

29
30
CALL BY REFERENCE

The call by reference method of passing arguments to a function copies the reference of an argument into
the formal parameter. Inside the function, the reference is used to access the actual argument used in the
call. This means that changes made to the parameter affect the passed argument.

To pass the value by reference, argument reference is passed to the functions just like any other value. So
accordingly you need to declare the function parameters as reference types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

// function definition to swap the values.

void swap(int &x, int &y) {

int temp;

temp = x; /* save the value at address x */

x = y; /* put y into x */

y = temp; /* put x into y */

return;

For now, let us call the function swap() by passing values by reference as in the following example −

#include <iostream>

// function declaration

void swap(int &x, int &y);

int main () {

// local variable declaration:

int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl;

cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/

swap(a, b);

cout << "After swap, value of a :" << a << endl;

cout << "After swap, value of b :" << b << endl;

return 0;

31
RETURN BY REFERENCE

Example:

#include <iostream>
using namespace std;
// Global variable
int num;
// Function declaration
Int& test();
int main()
{
test() = 5;
cout << num;
return 0;
}
Int& test()
{
return num;
}

In program above, the return type of function test() is int&. Hence, this function returns a
reference of the variable num.

The return statement is return num;. Unlike return by value, this statement doesn't return value
of num, instead it returns the variable itself (address).
Important Things to Remember When Returning by Reference.

 Ordinary function returns value but this function doesn't. Hence, you cannot return a
constant from the function.

int& test() {
return 2;
}

 You cannot return a local variable from this function.

int& test(){
int n = 2;
return n;
}

32
CLASSES AND OBJECTS
Class: The building block of C++ that leads to Object Oriented programming is a Class. It is a user defined
data type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behaviour
of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and member
functions can be apply brakes, increase speed etc.

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.

Defining Class and Declaring Objects


A class is defined in C++ using keyword class followed by the name of class. The body of class is defined
inside the curly brackets and terminated by a semicolon at the end.

Declaring Objects: When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:
ClassName ObjectName;

Accessing data members and member functions: The data members and member functions of class can be
accessed using the dot(‘.’) operator with the object. For example if the name of object is obj and you want to
access the member function with the name printName() then you will have to write obj.printName() .

Accessing Data Members

33
The public data members are also accessed in the same way given however the private data members are not
allowed to be accessed directly by the object. Accessing a data member depends solely on the access control
of that data member.
This access control is given by Access modifiers in C++. There are three access modifiers : public, private
and protected.

// C++ program to demonstrate 


// accessing of data members

#include <iostream.h>

class Geeks

    // Access specifier

    public:

    // Data Members

    string geekname;

    // Member Functions()

    void printname()

    {

       cout << "Geekname is: " << geekname;

    }

};

int main() {

    // Declare an object of class geeks

    Geeks obj1;

    // accessing data member

    obj1.geekname = "Abhi";

    // accessing member function

    obj1.printname();

    return 0;

Member Functions in Classes


There are 2 ways to define a member function:
 Inside class definition
 Outside class definition

To define a member function outside the class definition we have to use the scope resolution :: operator
along with class name and function name.

34
// C++ program to demonstrate function 
// declaration outside class

#include <iostream.h>

class Geeks

    public:

    string geekname;

    int id;

    // printname is not defined inside class defination

    void printname();

    // printid is defined inside class defination

    void printid()

    {

        cout << "Geek id is: " << id;

    }

};

// Definition of printname using scope resolution operator ::

void Geeks::printname()

    cout << "Geekname is: " << geekname;

int main() {

    Geeks obj1;

    obj1.geekname = "xyz";

    obj1.id=15;

    // call printname()

    obj1.printname();

    cout << endl;

    // call printid()

    obj1.printid();

    return 0;

35
Output:
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by default inline, but you can also
make any non-class function inline by using keyword inline with them. Inline functions are actual functions,
which are copied everywhere during compilation, like pre-processor macro, so the overhead of function
calling is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
Constructors
Constructors are special class members which are called by the compiler every time an object of that class is
instantiated. Constructors have the same name as the class and may be defined inside or outside the class
definition.
There are 3 types of constructors:
 Default constructors
 Parameterized constructors
 Copy constructors
// C++ program to demonstrate constructors

#include <iostream.h>

class Geeks

    public:

    int id;

    //Default Constructor

    Geeks()

    {

        cout << "Default Constructor called" << endl;

        id=-1;

    }

    //Parametrized Constructor

    Geeks(int x)

    {

        cout << "Parametrized Constructor called" << endl;

        id=x;

    }

};

36
int main() {

    // obj1 will call Default Constructor

    Geeks obj1;

    cout << "Geek id is: " <<obj1.id << endl;

    // obj1 will call Parametrized Constructor

    Geeks obj2(21);

    cout << "Geek id is: " <<obj2.id << endl;

    return 0;

Output:
Default Constructor called
Geek id is: -1
Parametrized Constructor called
Geek id is: 21
A Copy Constructor creates a new object, which is exact copy of the existing copy. The compiler provides
a default Copy Constructor to all the classes.
Syntax:
class-name (class-name &){}
Destructors
Destructor is another special member function that is called by the compiler when the scope of the object
ends.
// C++ program to explain destructors

#include <iostream.h>

class Geeks

    public:

    int id;

    //Definition for Destructor

    ~Geeks()

    {

        cout << "Destructor called for id: " << id <<endl;

    }

};

37
int main()

  {

    Geeks obj1;

    obj1.id=7;

    int i = 0;

    while ( i < 5 )

    {

        Geeks obj2;

        obj2.id=i;

        i++;

    } // Scope for obj2 ends here

    return 0;

  } // Scope for obj1 ends here

Output:
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7

Default Arguments in C++


A default argument is a value provided in function declaration that is automatically assigned by the compiler
if caller of the function doesn’t provide a value for the argument with default value.
Following is a simple C++ example to demonstrate use of default arguments. We don’t have to write 3 sum
functions, only one function works by using default values for 3rd and 4th arguments.
#include<iostream>
using namespace std;

// A function with default arguments, it can be called with


// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
    return (x + y + z + w);
}

/* Drier program to test above function*/


int main()
{
    cout << sum(10, 15) << endl;
    cout << sum(10, 15, 25) << endl;
    cout << sum(10, 15, 25, 30) << endl;

38
    return 0;
}

Key Points:
 Default arguments are different from constant arguments as constant arguments can’t be changed
whereas default arguments can be overwritten if required.
 Default arguments are overwritten when calling function provides values for them. For example,
calling of function sum(10, 15, 25, 30) overwrites the value of z and w to 25 and 30 respectively.
 During calling of function, arguments from calling function to called function are copied from left to
right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y and z. Therefore, default value is
used for w only.
 Once default value is used for an argument in function definition, all subsequent arguments to it must
have default value. It can also be stated as default arguments are assigned from right to left. For
example, the following function definition is invalid as subsequent argument of default variable z is not
default.

// Invalid because z has default value, but w after it


// doesn't have default value
int sum(int x, int y, int z=0, int w)

const Function Arguments and Return types


We can make the return type or arguments of a function as const. Then we cannot change any of them.
void f(const int i)
{
i++; // error
}
const int g()
{
return 1;
}

Some Important points to Remember

1. For built in datatypes, returning a const or non-const value, doesn't make any difference.

const int h()


{
return 1;
}
int main()
{
const int j = h();
int k = h();
}

Both j and k will be assigned the value 1. No error will occur.

2. For user defined datatypes, returning const, will prevent its modification.

39
3. Temporary objects created while program execution are always of const type.
4. If a function has a non-const parameter, it cannot be passed a const argument while making a call.

void t(int*)
{
// function logic
}

If we pass a const int* argument to the function t, it will give error.

5. But, a function which has a const type parameter, can be passed a const type argument as well as a non-
const argument.

void g(const int*)


{
// function logic
}

This function can have a int* as well as const int* type argument.

 Function Overloading
Two or more functions having same name but different argument(s) are known as overloaded functions. In
this article, you will learn about function overloading with examples.

Function refers to a segment that groups code to perform a specific task.

In C++ programming, two functions can have same name if number and/or type of arguments passed are
different.

These functions having different number or type (or both) of parameters are known as overloaded functions.
For example:

40
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

Here, all 4 functions are overloaded functions because argument(s) passed to these functions are different.

Notice that, the return type of all these 4 functions are not same. Overloaded functions may or may not have
different return type but it should have different argument(s).

// Error code
int test(int a) { }
double test(int b){ }

The number and type of arguments passed to these two functions are same even though the return type is
different. Hence, the compiler will throw error.

Example 1: Function Overloading

#include <iostream.h>
void display(int);
void display(float);
void display(int, float);
int main() {
int a = 5;
float b = 5.5;
display(a);
display(b);
display(a, b);
return 0;
}
void display(int var) {
cout << "Integer number: " << var << endl;
}
void display(float var) {
cout << "Float number: " << var << endl;
}
void display(int var1, float var2) {
cout << "Integer number: " << var1;

41
cout << " and float number:" << var2;
}

Output
Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5

Here, the display() function is called three times with different type or number of arguments.
The return type of all these functions are same but it's not necessary.

Example 2: Function Overloading


// Program to compute absolute value
// Works both for integer and float
#include <iostream.h>
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

Output

42
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5

In the above example, two functions absolute() are overloaded.

Both functions take single argument. However, one function takes integer as an argument and other takes
float as an argument.

When absolute() function is called with integer as an argument, this function is called:

int absolute(int var) {


if (var < 0)
var = -var;
return var;
}

When absolute() function is called with float as an argument, this function is called:

float absolute(float var){


if (var < 0.0)
var = -var;
return var;
}

Virtual Functions
A virtual function a member function which is declared within base class and is re-defined (Overriden) by
derived class. When you refer to a derived class object using a pointer or a reference to the base class, you
can call a virtual function for that object and execute the derived class’s version of the function.
 Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.

Rules for Virtual Functions


1. They Must be declared in public section of class.
2. Virtual functions cannot be static and also cannot be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to achieve run time
polymorphism.
4. The prototype of virtual functions should be same in base as well as derived class.
5. They are always defined in base class and overridden in derived class. It is not mandatory for derived
class to override (or re-define the virtual function), in that case base class version of function is used.
6. A class may have virtual destructor but it cannot have a virtual constructor.

EXAMPLE :

43
// CPP program to illustrate
// concept of Virtual Functions
#include<iostream.h>

class base
{
public:
    virtual void print ()
    { cout<< "print base class" <<endl; }

    void show ()
    { cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
    void print ()
    { cout<< "print derived class" <<endl; }

    void show ()
    { cout<< "show derived class" <<endl; }
};

int main()
{
    base *bptr;
    derived d;
    bptr = &d;

    //virtual function, binded at runtime


    bptr->print();

    // Non-virtual function, binded at compile time


    bptr->show();
}
Output:
print derived class
show base class

Friend Functions
A friend function of a class is defined outside that class' scope but it has the right to access all private and
protected members of the class. Even though the prototypes for friend functions appear in the class
definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which
case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in the class definition with
keyword friend as follows −
class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

44
To declare all member functions of class ClassTwo as friends of class ClassOne, place a following
declaration in the definition of class ClassOne −
friend class ClassTwo;

Consider the following program −

#include <iostream.h>

class Box {

double width;

public:

friend void printWidth( Box box );

void setWidth( double wid );

};

// Member function definition

void Box::setWidth( double wid ) {

width = wid;

// Note: printWidth() is not a member function of any class.

void printWidth( Box box ) {

/* Because printWidth() is a friend of Box, it can

directly access any member of this class */

cout << "Width of box : " << box.width <<endl;

// Main function for the program

int main() {

Box box;

// set box width without member function

box.setWidth(10.0);

// Use friend function to print the wdith.

printWidth( box );

return 0;

When the above code is compiled and executed, it produces the following result −
Width of box : 10

45
46
Arrays within a Class

 Arrays can be declared as the members of a class.


 The arrays can be declared as private, public or protected members of the class.
 To understand the concept of arrays as members of a class, consider this example.

A program to demonstrate the concept of arrays as class members


Example:

#include<iostream.h>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

47
Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343

Memory Allocation for Objects


Before using a member of a class, it is necessary to allocate the required memory space to that member. The
way the memory space for data members and member functions is allocated is different regardless of the fact
that both data members and member functions belong to the same class.
The memory space is allocated to the data members of a class only when an object of the class is declared,
and not when the data members are declared inside the class. Since a single data member can have different
values for different objects at the same time, every object declared for the class has an individual copy of all
the data members.
On the other hand, the memory space for the member functions is allocated only once when the class is
defined. In other words, there is only a single copy of each member function, which is shared among all the
objects. For instance, the three objects, namely, book1, book2 and book3 of the class book have individual
copies of the data members title and price. However, there is only one copy of the member functions getdata
() and putdata () that is shared by all the three objects

                           

STATIC MEMBERS OF A CLASS


We can define class members static using static keyword. When we declare a member of a class as static it
means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first
object is created, if no other initialization is present. We can't put it in the class definition but it can be
initialized outside the class as done in the following example by redeclaring the static variable, using the
scope resolution operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members
48
#include <iostream.h>

class Box {

public:

static int objectCount;

// Constructor definition

Box(double l = 2.0, double b = 2.0, double h = 2.0) {

cout <<"Constructor called." << endl;

length = l;

breadth = b;

height = h;

// Increase every time object is created

objectCount++;

double Volume() {

return length * breadth * height;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

// Initialize static member of class Box

int Box::objectCount = 0;

int main(void) {

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.

cout << "Total objects: " << Box::objectCount << endl;

return 0;

When the above code is compiled and executed, it produces the following result −
Constructor called.

49
Constructor called.
Total objects: 2

Static Function Members


By declaring a function member as static, you make it independent of any particular object of the class. A
static member function can be called even if no objects of the class exist and the static functions are
accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other
functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You
could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members

#include <iostream.h>

class Box {

public:

static int objectCount;

// Constructor definition

Box(double l = 2.0, double b = 2.0, double h = 2.0) {

cout <<"Constructor called." << endl;

length = l;

breadth = b;

height = h;

// Increase every time object is created

objectCount++;

double Volume() {

return length * breadth * height;

static int getCount() {

return objectCount;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

50
};

// Initialize static member of class Box

int Box::objectCount = 0;

int main(void) {

// Print total number of objects before creating object.

cout << "Inital Stage Count: " << Box::getCount() << endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects after creating object.

cout << "Final Stage Count: " << Box::getCount() << endl;

return 0;

When the above code is compiled and executed, it produces the following result −
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

Array of Objects
Now, suppose we have 50 students in a class and we have to input the name and marks of all the 50 students.
Then creating 50 different objects and then inputting the name and marks of all those 50 students is not a
good option. In that case, we will create an array of objects as we do in case of other data-types.
Let's see an example of taking the input of name and marks of 5 students by creating an array of the objects
of students.

#include <iostream>
#include <string>
class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;

51
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}

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


{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0;
}

Now let’s go through this code.


Student st[5]; - We created an array of 5 objects of the Student class where each object represents a student
having a name and marks.
The first for loop is for taking the input of name and marks of the students. getName() and getMarks() are
the functions to take the input of name and marks respectively.
The second for loop is to print the name and marks of all the 5 students. For that, we called
the displayInfo()function for each student.

52
Objects as function Arguments
The objects of a class can be passed as arguments to member functions as well as non-member functions
either by value or by reference. When an object is passed by value, a copy of the actual object is created
inside the function. This copy is destroyed when the function terminates. Moreover, any changes made to the
copy of the object inside the function are not reflected in the actual object. On the other hand, in pass by
reference, only a reference to that object (not the entire object) is passed to the function. Thus, the changes
made to the object within the function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members can be
accessed inside the function using the object name and the dot operator. However, the data members of the
calling object can be directly accessed inside the function without using the object name and the dot
operator.
To understand how objects are passed and accessed within a member function, consider this example.
Example: A program to demonstrate passing objects by value to a member function of the same class
 
#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
} ;
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
void weight :: sum_weight(weight wl,weight w2)
{
gram = wl.gram + w2.gram;
kilogram=gram/1000;
gram=gram%1000;
kilogram+=wl.kilogram+w2.kilogram;

53
}
int main ()
{
weight wl,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
wl.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
wl.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
 

The output of the program is


 
Enter weight in kilograms and grams
Enter weight #1
Kilograms: 12
Grams: 560
Enter weight #2
Kilograms: 24
Grams: 850
Weight #1 = 12 Kgs. and 560 gms.
Weight #2 = 24 Kgs. and 850 gms.
Total Weight = 37 Kgs. and 410 gms.

POINTERS TO MEMBERS
Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to
member to point to a static class member because the address of a static member is not associated with any
particular object. To point to a static class member, you must use a normal pointer.

You can use pointers to member functions in the same manner as pointers to functions. You can compare
pointers to member functions, assign values to them, and use them to call member functions. Note that a

54
member function does not have the same type as a nonmember function that has the same number and type
of arguments and the same return type.

Pointers to members can be declared and used as shown in the following example:
#include <iostream>
using namespace std;

class X {
public:
int a;
void f(int b) {
cout << "The value of b is "<< b << endl;
}
};
int main() {
// declare pointer to data member
int X::*ptiptr = &X::a;
// declare a pointer to member function
void (X::* ptfptr) (int) = &X::f;
// create an object of class type X
X xobject;
// initialize data member
xobject.*ptiptr = 10;
cout << "The value of a is " << xobject.*ptiptr << endl;

// call member function


(xobject.*ptfptr) (20);
}

The output for this example is:


The value of a is 10
The value of b is 20

To reduce complex syntax, you can declare a typedef to be a pointer to a member. A pointer to a member
can be declared and used as shown in the following code fragment:

typedef int X::*my_pointer_to_member;


typedef void (X::*my_pointer_to_function) (int);

int main() {
my_pointer_to_member ptiptr = &X::a;
my_pointer_to_function ptfptr = &X::f;
X xobject;
xobject.*ptiptr = 10;
cout << "The value of a is " << xobject.*ptiptr << endl;
(xobject.*ptfptr) (20);
}

The pointer to member operators .* and ->* are used to bind a pointer to a member of a specific class object.
Because the precedence of ()(function call operator) is higher than .* and ->*, you must use parentheses to
call the function pointed to by ptf.

Pointer-to-member conversion can occur when pointers to members are initialized, assigned, or compared.
Note that pointer to a member is not the same as a pointer to an object or a pointer to a function.

55
POINTERS TO CONSTRUCTORS / CLASSES

A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a
pointer to a class you use the member access operator -> operator, just as you do with pointers to structures.
Also as with all pointers, you must initialize the pointer before using it.

Let us try the following example to understand the concept of pointer to a class

#include <iostream.h>

class Box {

public:

// Constructor definition

Box(double l = 2.0, double b = 2.0, double h = 2.0) {

cout <<"Constructor called." << endl;

length = l;

breadth = b;

height = h;

double Volume() {

return length * breadth * height;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

int main(void) {

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

Box *ptrBox; // Declare pointer to a class.

// Save the address of first object

ptrBox = &Box1;

// Now try to access a member using member access operator

56
cout << "Volume of Box1: " << ptrBox->Volume() << endl;

// Save the address of second object

ptrBox = &Box2;

// Now try to access a member using member access operator

cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;

When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102

TYPES OF EXPRESSIONS

57
UNIT III

OPERATOR OVERLOADING
Overloading is not possible for the following operators

 Class member operators (.,.*)


 Scope resolution operator (::)
 Size operator:(sizeof)
 Conditional Operator(?:)

Operator Function

return-type classname :: operator <op>(arg list)

 operator <op> is the function name


 Operator functions must be either (non static) member functions or friend functions
 Objects used to invoke operator is passed implicitly the operator function
 Passing by value or passing by variable accepted
 The interpretation is like a function only

Example :

Overloading minus operator (-)

class space
{ int x,y,z;
   public:
     void getdata(int a, int b, int c);
     void display(void);
     void operator-(); }
void space :: operator –()
    { x = -x; y = -y; z = -z; }
main ()
{ space s; s.getdata(10,-20,30); s.display();
  -s; s.display(); }

Overriding plus operator (+)

class complex
{ float x,y;
   public : ….
// complex sum (complex c)
   complex operator+(complex c)
{ complex temp;
   temp.x = x + c.x;   temp.y = x + c.y; return temp}
main();
{ complex c1,c2,c3;
 // c3 = c1.sum(c2);
    c3 = c1 + c2;   }

58
TYPE CONVERSIONS

A type cast is basically a conversion from one type to another.

The process of converting one predefined type into another is called as type conversion. When constants and
variables of different types are mixed in an expression, they are converted to the same type. When variables
of one type are mixed with variables of another type, a type conversion will occur. C++ facilitates the type
conversion into the following two forms :

 Implicit Type Conversion


 Explicit Type Conversion

Implicit Type Conversion

An implicit type conversion is a conversion performed by the compiler without programmer's intervention.
An implicit conversion is applied generally whenever differing data types are intermixed in an expression
(mixed mode expression), so as not to lose information. The value of the right side (expression side) of the
assignment is converted to the type of the left side (target variable).

Therefore, the types of right side and left side of an assignment should be compatible so that type
conversion can take place. The compatible data types are mathematical data types i.e., char, int ,float,
double. For example, the following statement :

ch = x ; (where ch is char and x is int)

Converts the value of x i.e., integer to bit into ch, a character. Assuming that word size is 16-bit (2 bytes),
the left higher order bits of the integer variable x are looped off, leaving ch with lower 8-bits. Say, if x was
having value 1417 (whose binary equivalent is 0000010110001001) the ch will have lower 8-bits i.e.,
10001001 resulting in loss of information.

The C++ compiler converts all operands upto the type of the largest operand, which is called type promotion.
This is done operation by operation, as described in the following type conversion algorithm :

 If either operand is of type long double, the other is converted to long double.
 Otherwise, if either operand is of type double, the other is converted to double.
 Otherwise, if either operand is float, the other is converted to float.
 Otherwise, the integral promotions are performed on both operands. The process of integral
promotion is described below :

 A char, a short int, enumerator or an int (in both their signed and unsigned varieties) may be used as
an integer type. If an int can represent all the values of the original type, the value is converted to int ;
otherwise it is converted to unsigned int. This process is called integral promotion.
 Then, if either operand is unsigned long, the other is converted to unsigned long.
 Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all
the values of an unsigned int, the unsigned int is converted to long int; otherwise both operands are
converted to unsigned long int.
 Otherwise, if either operand is long, the other is converted to long.
 Otherwise, if either operand is unsigned, the other is converted to unsigned.

59
 Otherwise, both operands are int.

When converting from integers to characters and long integers to integers, the appropriate amount of high-
orders bits (depending upon target type's size) will be removed. In many environments, this means that 8 bits
will be lost when going from an integer to a character and 16 bits will be lost when going from a long integer
to an integer.

The following table summarizes the assignment type conversions :

Remember - When conversion takes place from smaller type to longer type e.g., from int to float or a float to
a double, there is no loss of information. Neither does it add any precision or accuracy. These kinds of
conversions only change the form in which the value is represented.

Explicit Type Conversion - Type Casting

The explicit conversion of an operand to a specific type is called type casting. An explicit type conversion is
user-defined that forces an expression to be of specific type.This is the general form to perform type casting
in C++

(type) expression

where type is a valid C++ data type to which the conversion is to be done. For example, to make sure that
expression (x + y/2) evaluates to type float, write it as :

(float) (x + y/2)

As you can see from the above statement, the resultant types of the right side can be converted explicitly
using type casting operator (). For example, the resultant type of the following expression side is double.

int i, j;
float f, result;
double d;
result = (i/j) + (f/d) - (f+i);

If you want to convert the type of expression side to float explicitly, it can be done as shown below:

60
result = (float) ( (i/j) + (f/d) - (f+i));

Casts are often considered as operators. As an operator, a cast is unary and has the same precedence as any
other unary operator. Here is an example

/* C++ Type Conversion and Type Casting */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float res;
float f1=15.5, f2=2;
res = (int)f1/(int)f2;
cout<<res<<endl;
res = (int)(f1/f2);
cout<<res<<endl;
res = f1/f2;
cout<<res;
getch();
}

Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create these classes
avoiding inheritance then we have to write all of these functions in each of the three classes as shown in
below figure:

You can clearly see that above process results in duplication of same code 3 times. This increases the
chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class
Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we
can simply avoid the duplication of data and increase re-usability. Look at the below diagram in which the
three classes are inherited from vehicle class:

61
Using inheritance, we have to write the functions only one time instead of three times as we have inherited
rest of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have to
follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit
this sub class for example: public, private etc. and base_class_name is the name of the base class from
which you want to inherit the sub class.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent
object, which contains any private members which that class declares.

// C++ program to demonstrate implementation of Inheritance

#include <iostream.h>

//Base class

class Parent

    public:

    int id_p;

};

// Sub class inheriting from Base Class(Parent)

class Child : public Parent

{  public:

      int id_c; };

//main function

int main()

   {

        Child obj1;

        // An object of class child has all data members

        // and member functions of class parent

62
        obj1.id_c = 7;

        obj1.id_p = 91;

        cout << "Child id is " <<  obj1.id_c << endl;

        cout << "Parent id is " <<  obj1.id_p << endl;

        return 0;

   }

Output:
Child id is 7
Parent id is 91
In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data
members of the class ‘Parent’ will also be inherited by the class ‘Child’.

Modes of Inheritance

1. Public mode: If we derive a sub class from a public base class. Then the public member of the base
class will become public in the derived class and protected members of the base class will become
protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both public member and
protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Note : The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed. For example, Classes B, C and D all contain the variables x, y
and z in below example. It is just question of access.

// C++ Implementation to show that a derived class

// doesn’t inherit access to private data members.

// However, it does inherit a full parent object

class A

public:

    int x;

protected:

    int y;

private:

    int z;

};

class B : public A

63
    // x is public

    // y is protected

    // z is not accessible from B

};

class C : protected A

    // x is protected

    // y is protected

    // z is not accessible from C

};

class D : private A    // 'private' is default for classes

    // x is private

    // y is private

    // z is not accessible from D

};

The below table summarizes the above three modes and shows the access specifier of the members of base
class in the sub class when derived in public, protected and private modes:

64
Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one sub
class is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};

// C++ program to explain

// Single inheritance

#include <iostream.h>

// base class

class Vehicle {

  public:

    Vehicle()

    { cout << "This is a Vehicle" << endl; }

};

// sub class derived from two base classes

class Car: public Vehicle{

};

// main function

int main()

    // creating object of sub class will

    // invoke the constructor of base classes

    Car obj;

    return 0; }

65
Output:
This is a vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more
than one classes. i.e one sub class is inherited from more than one base classes.

Syntax:
class subclass_name : access_mode base_class1, access_mode
base_class2, ....
{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for every base
class must be specified.

// C++ program to explain

// multiple inheritance

#include <iostream.h>

// first base class

class Vehicle {

  public:

    Vehicle()

    {

      cout << "This is a Vehicle" << endl;

    }

};

// second base class

class FourWheeler {

  public:

    FourWheeler()

    {

66
      cout << "This is a 4 wheeler Vehicle" << endl;

    } };

// sub class derived from two base classes

class Car: public Vehicle, public FourWheeler {

};

// main function

int main()

    // creating object of sub class will

    // invoke the constructor of base classes

    Car obj;

    return 0;

Output:
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived

class.

// C++ program to implement

// Multilevel Inheritance

#include <iostream.h>

67
// base class

class Vehicle

  public:

    Vehicle()

    {

      cout << "This is a Vehicle" << endl;

    }

};

class fourWheeler: public Vehicle

{  public:

    fourWheeler()

    {

      cout<<"Objects with 4 wheels are vehicles"<<endl;

    }

};

// sub class derived from two base classes

class Car: public fourWheeler{

   public:

     car()

     {

       cout<<"Car has 4 Wheels"<<endl;

     }

};

// main function

int main()

    //creating object of sub class will

    //invoke the constructor of base classes

    Car obj;

    return 0;

output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels

68
4. Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a single base class.

// C++ program to implement

// Hierarchical Inheritance

#include <iostream.h>

// base class

class Vehicle

  public:

    Vehicle()

    {

      cout << "This is a Vehicle" << endl;

    }

};

// first sub class

class Car: public Vehicle

};

// second sub class

class Bus: public Vehicle

};

69
// main function

int main()

    // creating object of sub class will

    // invoke the constructor of base class

    Car obj1;

    Bus obj2;

    return 0;

Output:
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type
of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:

// C++ program for Hybrid Inheritance

#include <iostream>

// base class

class Vehicle

  public:

    Vehicle()

    {

70
      cout << "This is a Vehicle" << endl;

    }

};

//base class

class Fare

    public:

    Fare()

    {

        cout<<"Fare of Vehicle\n";

    }

};

// first sub class

class Car: public Vehicle

};

// second sub class

class Bus: public Vehicle, public Fare

};

// main function

int main()

    // creating object of sub class will

    // invoke the constructor of base class

    Bus obj2;

    return 0;

Output:
This is a Vehicle
Fare of Vehicle

71
VIRTUAL BASE CLASS
An uncertainity can arise when several paths exist to a class from the same base class. This means that a
child class could have duplicate sets of members inherited from a single base class.
C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is
taken so that the duplication is avoided regardless of the number of paths that exist to the child class.

When two or more objects are derived from a common base class, we can prevent multiple copies of the
base class being present in an object derived from those objects by declaring the base class as virtual when it
is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the
base class’ name with the word virtual.

Consider the following example :


class A 

   public: 
       int i; 
};
class B : virtual public A 

   public: 
       int j; 
};
class C: virtual public A 

   public: 
       int k; 
};
class D: public B, public C 

   public: 
       int sum; 
};
int main() 

   D ob; 
   ob.i = 10; //unambiguous since only one copy of i is inherited. 
   ob.j = 20; 
   ob.k = 30; 
   ob.sum = ob.i + ob.j + ob.k; 
   cout << “Value of i is : ”<< ob.i<<”\n”; 
   cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”; 
   cout << “Sum is : ”<< ob.sum <<”\n”; 

72
   return 0; 
}

ABSTRACT CLASS
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains
at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the
declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:
class AB {
public:
virtual void f() = 0;
};
Function AB::f is a pure virtual function. A function declaration cannot have both a pure specifier and a
definition. For example, the compiler will not allow the following:
struct A {
virtual void g() { } = 0;
};
You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit
conversion, nor can you declare an object of an abstract class. You can, however, declare pointers and
references to an abstract class. The following example demonstrates this:
struct A {
virtual void f() = 0;
};

struct B : A {
virtual void f() { }
};

// Error:
// Class A is an abstract class
// A g();

// Error:
// Class A is an abstract class
// void h(A);
A& i(A&);

int main() {

// Error:
// Class A is an abstract class
// A a;

A* pa;
B b;

// Error:
// Class A is an abstract class
// static_cast<A>(b);
}

Class A is an abstract class. The compiler would not allow the function declarations A g() or void h(A),
declaration of object a, nor the static cast of b to type A.

73
Virtual member functions are inherited. A class derived from an abstract base class will also be abstract
unless you override each pure virtual function in the derived class.

For example:
class AB {
public:
virtual void f() = 0;
};

class D2 : public AB {
void g();
};

int main() {
D2 d;
}
The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure
virtual function f()from AB. The compiler will allow the declaration of object d if you define
function D2::f(), as this overrides the inherited pure virtual function AB::f(). Function AB::f() needs to be
overridden if you want to avoid the abstraction of D2.
Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual
function with a pure virtual function.
You can call member functions from a constructor or destructor of an abstract class. However, the results of
calling (directly or indirectly) a pure virtual function from its constructor are undefined. The following
example demonstrates this:
struct A {
A() {
direct();
indirect();
}
virtual void direct() = 0;
virtual void indirect() { direct(); }
};
The default constructor of A calls the pure virtual function direct() both directly and indirectly
(through indirect()).
The compiler issues a warning for the direct call to the pure virtual function, but not for the indirect call.

VIRTUAL FUNCTIONS
By default, C++ matches a function call with the correct function definition at compile time. This is
called static binding. You can specify that the compiler match a function call with the correct function
definition at run time; this is called dynamic binding. You declare a function with the keyword virtual if you
want the compiler to use dynamic binding for that specific function.
The following examples demonstrate the differences between static and dynamic binding. The first example
demonstrates static binding:

#include <iostream>
struct A {
void f() { cout << "Class A" << endl; }
};

struct B: A {

74
void f() { cout << "Class B" << endl; }
};

void g(A& arg) {


arg.f();
}

int main() {
B x;
g(x);
}
The following is the output of the above example:
Class A

When function g() is called, function A::f() is called, although the argument refers to an object of type B. At
compile time, the compiler knows only that the argument of function g() is an lvalue reference to an object
derived from A; it cannot determine whether the argument is an lvalue reference to an object of type A or
type B. However, this can be determined at run time. The following example is the same as the previous
example, except that A::f() is declared with the virtual keyword:

#include <iostream.h>
struct A {
virtual void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};

void g(A& arg) {


arg.f();
}
int main() {
B x;
g(x);
}

The following is the output of the above example:


Class B

The virtual keyword indicates to the compiler that it should choose the appropriate definition of f() not by
the type of lvalue reference, but by the type of object that the lvalue reference refers to.
Therefore, a virtual function is a member function you may redefine for other derived classes, and can
ensure that the compiler will call the redefined virtual function for an object of the corresponding derived
class, even if you call that function with a pointer or reference to a base class of the object.
A class that declares or inherits a virtual function is called a polymorphic class.

POLYMORPHISM
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed
depending on the type of object that invokes the function.

Consider the following example where a base class has been derived by other two classes −

75
#include <iostream.h>

class Shape {

protected:

int width, height;

public:

Shape( int a = 0, int b = 0){

width = a;

height = b;

int area() {

cout << "Parent class area :" <<endl;

return 0;

};

class Rectangle: public Shape {

public:

Rectangle( int a = 0, int b = 0):Shape(a, b) {

int area () {

cout << "Rectangle class area :" <<endl;

return (width * height);

};

class Triangle: public Shape {

public:

Triangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {

cout << "Triangle class area :" <<endl;

return (width * height / 2);

};

// Main function for the program

int main() {

Shape *shape;

76
Rectangle rec(10,7);

Triangle tri(10,5);

// store the address of Rectangle

shape = &rec;

// call rectangle area.

shape->area();

// store the address of Triangle

shape = &tri;

// call triangle area.

shape->area();

return 0;

When the above code is compiled and executed, it produces the following result −

Parent class area :


Parent class area :
The reason for the incorrect output is that the call of the function area() is being set once by the compiler as
the version defined in the base class. This is called static resolution of the function call, or static linkage -
the function call is fixed before the program is executed. This is also sometimes called early
binding because the area() function is set during the compilation of the program.

But now, let's make a slight modification in our program and precede the declaration of area() in the Shape
class with the keyword virtual so that it looks like this −

class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and executed, it produces the
following result −

Rectangle class area


Triangle class area

77
This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of
objects of tri and rec classes are stored in *shape the respective area() function is called.

As you can see, each of the child classes has a separate implementation for the function area(). This is
how polymorphism is generally used. You have different classes with a function of the same name, and
even the same parameters, but with different implementations.

POINTERS
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer
variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the
valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same,
a long hexadecimal number that represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the pointer points to.

Using Pointers in C++


There are few important operations, which we will do with the pointers very frequently. (a) We define a
pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the value at the address
available in the pointer variable. This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand. Following example makes use of these operations

#include <iostream.h>

int main () {

int var = 20; // actual variable declaration.

int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";

cout << var << endl;

// print the address stored in ip pointer variable

cout << "Address stored in ip variable: ";

cout << ip << endl;

78
// access the value at the address available in pointer

cout << "Value of *ip variable: ";

cout << *ip << endl;

return 0;

When the above code is compiled and executed, it produces result something as follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

POINTERS TO OBJECTS

C++ allows you to have pointers to objects. The pointers pointing to objects are referred to as Object
Pointers.

Just like other pointers, the object pointers are declared by placing in front of a object pointer's name. It takes
the following general form :

class-name ∗ object-pointer ;

where class-name is the name of an already defined class and object-pointer is the pointer to an object of this
class type. For example, to declare optr as an object pointer of Sample class type, we shall write

Sample ∗optr ;

where Sample is already defined class. When accessing members of a class using an object pointer, the
arrow operator (->) is used instead of dot operator.

The following program illustrates how to access an object given a pointer to it. This C++ program illustrates
the use of object pointer

/* C++ Pointers and Objects. Declaration and Use


* of Pointers. This program demonstrates the
* use of pointers in C++ */

#include<iostream.h>
#include<conio.h>
class Time
{
short int hh, mm, ss;
public:
Time()
{
hh = mm = ss = 0;
}
void getdata(int i, int j, int k)
{
hh = i;

79
mm = j;
ss = k;
}
void prndata(void)
{
cout<<"\nTime is "<<hh<<":"<<mm<<":"<<ss<<"\n";
}
};
void main()
{
clrscr();
Time T1, *tptr;
cout<<"Initializing data members using the object, with values 12, 22,
11\n";
T1.getdata(12,22,11);
cout<<"Printing members using the object ";
T1.prndata();
tptr = &T1;
cout<<"Printing members using the object pointer ";
tptr->prndata();
cout<<"\nInitializing data members using the object pointer, with values
15, 10, 16\n";
tptr->getdata(15, 10, 16);
cout<<"printing members using the object ";
T1.prndata();
cout<<"Printing members using the object pointer ";
tptr->prndata();
getch();
}

this Pointer

As soon as you define a class, the member functions are created and placed in the memory space only once.
That is, only one copy of member functions is maintained that is shared by all the objects of the class. Only
space for data members is allocated separately for each object (See the following figure).

80
This has an associated problem. If only one instance of a member function exists, how does it come to know
which object's data member is to be manipulated ? For example, if member function 3 is capable of changing
the value of data member2 and we want to change the value of data member2 of object1. How could the
member function3 come to know which object's data member2 is to be changed ?

The answer to this problem is this pointer. When a member function is called, it is automatically passed an
implicit (in-built) argument that is a pointer to the object that invoked the function. This pointer is called
this. That is if object1 is invoking member function3, then an implicit argument is passed to member
function3 that points to object1 i.e., this pointer now points to object1. The this pointer can be thought of
analogous to the ATM card. For instance, in a bank there are many accounts. The account holders can
withdraw amount or view their bank-statements through Automatic-Teller-Machines. Now, these ATMs can
withdraw from any account in the bank, but which account are they supposed to work upon ? This is
resolved by the ATM card, which gives the identification of user and his accounts, from where the amount is
withdrawn.

Similarly, the this pointer is the ATM cards for objects, which identifies the currently-calling object. The this
pointer stores the address of currently-calling object. To understand this, consider the following example
program (following program illustrates the functioning of this pointer) :

/* C++ Pointers and Objects. The this pointer.


* This C++ program demonstrates about the this
* pointer in C++ */

#include<iostream.h>
#include<conio.h>
#include<string.h>
class Salesman
{
char name[1200];
float total_sales;
public:
Salesman(char *s, float f)
{
strcpy(name, "“;
strcpy(name, s);
total_sales = f;
}
void prnobject(void)
{
cout.write(this->name, 26); // use of this pointer
cout<<" has invoked prnobject().\n";
}
};
void main()
{
clrscr();
Salesman Rajat("Rajat", 21450), Ravi("Ravi", 23190), Vikrant("Vikrant",
19142);
/* above statement creates three objects */
Rajat.prnobject();
81
Vikrant.prnobject();
Ravi.prnobject();
getch();
}

POINTER TO DERIVED CLASS

In C++, we can declare a pointer points to the base class as well as derive class. 
Consider below example to understand pointer to derived class

#include<iostream.h>
class base
{
public:
int n1;
void show()
{
cout<<”\nn1 = “<<n1;
}
};
class derive : public base
{
public:
int n2;
void show()
{
cout<<”\nn1 = “<<n1;
cout<<”\nn2 = “<<n2;
}
};
int main()
{
base b;
base *bptr; //base pointer
cout<<”Pointer of base class points to it”;
bptr=&b; //address of base class
bptr->n1=44; //access base class via base pointer
bptr->show();
derive d;
cout<<”\n”;
bptr=&d; //address of derive class
bptr->n1=66; //access derive class via base pointer
bptr->show();
return 0;
}
Output
Pointer of base class points to it
n1 = 44
Pointer of base class points to derive class
n1=66

82
UNIT IV : C++ FILES AND STREAMS
So far, we have been using the iostream standard library, which provides cinand cout methods for reading
from standard input and writing to standard output respectively.

This tutorial will teach you how to read and write from a file. This requires another standard C++ library
called fstream, which defines three new data types −

Sr.No Data Type & Description

1 ofstream

This data type represents the output file stream and is used to create files and to write
information to files.

2
ifstream

This data type represents the input file stream and is used to read information from files.

3 fstream

This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and
read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++
source file.

Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be
used to open a file for writing. And ifstream object is used to open a file for reading purpose only.

Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream
objects.

void open(const char *filename, ios::openmode mode);


Here, the first argument specifies the name and location of the file to be opened and the second argument of
the open() member function defines the mode in which the file should be opened.

Sr.No Mode Flag & Description

1
ios::app

Append mode. All output to that file to be appended to the end.

2 ios::ate

83
Open a file for output and move the read/write control to the end of the file.

3
ios::in

Open a file for reading.

4 ios::out

Open a file for writing.

5
ios::trunc

If the file already exists, its contents will be truncated before opening the file.

You can combine two or more of these values by ORing them together. For example if you want to open a
file in write mode and want to truncate it in case that already exists, following will be the syntax −

ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −

fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory
and close all the opened files. But it is always a good practice that a programmer should close all the
opened files before program termination.

Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream
objects.

void close();

Writing to a File
While doing C++ programming, you write information to a file from your program using the stream
insertion operator (<<) just as you use that operator to output information to the screen. The only difference
is that you use an ofstream or fstream object instead of the cout object.

Reading from a File


You read information from a file into your program using the stream extraction operator (>>) just as you
use that operator to input information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.

Read and Write Example

84
Following is the C++ program which opens a file in reading and writing mode. After writing information
entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto
the screen −

#include <fstream.h>

#include <iostream.h>

int main () {

char data[100];

// open a file in write mode.

ofstream outfile;

outfile.open("afile.dat”;

cout << "Writing to the file" << endl;

cout << "Enter your name: ";

cin.getline(data, 100);

// write inputted data into the file.

outfile << data << endl;

cout << "Enter your age: ";

cin >> data;

cin.ignore();

// again write inputted data into the file.

outfile << data << endl;

// close the opened file.

outfile.close();

// open a file in read mode.

ifstream infile;

infile.open("afile.dat”;

cout << "Reading from the file" << endl;

infile >> data;

// write the data at the screen.

cout << data << endl;

// again read the data from the file and display it.

infile >> data;

85
cout << data << endl;

// close the opened file.

infile.close();

return 0;

When the above code is compiled and executed, it produces the following sample input and output −

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read the line
from outside and ignore() function to ignore the extra characters left by previous read statement.

File Position Pointers


Both istream and ostream provide member functions for repositioning the file-position pointer. These
member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.

The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate
the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning
of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning
relative to the end of a stream.

The file-position pointer is an integer value that specifies the location in the file as a number of bytes from
the file's starting location. Some examples of positioning the "get" file-position pointer are −

// position to the nth byte of fileObject (assumes ios::beg)


fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );
C++ STREAMS
C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just like
water and oil flowing through a pipe). In input operations, data bytes flow from an input source (such as
keyboard, file, network or another program) into the program. In output operations, data bytes flow from the
program to an output sink (such as console, file, network or another program). Streams acts as an
intermediaries between the programs and the actual IO devices, in such the way that frees the programmers
from handling the actual devices, so as to archive device independent IO operations.

86
87
FORMATTING OUTPUT USING MANIPULATORS

Formatted output is very important in development field for easily read and understand.C++ offers the
several input/output manipulators for formatting, commonly used manipulators are given below..

Manipulator Declaration in

endl iostream.h

setw iomanip.h

setprecision iomanip.h

setf iomanip.h

endl

endl manipulator is used to Terminate a line and flushes the buffer.

Difference b/w '\n' and endl

When writing output in C++,you can use either std::endl or '\n' to produce a newline, but each has a different
effect.

 std::endl sends a newline character '\n' and flushes the output buffer.
 '\n' sends the newline character, but does not flush the output buffer.

The distinction is very important if you're writing debugging messages that you really need to see
immediately, you should always use std::endl rather than '\n' to force the flush to take place immediately.

The following is an example of how to use both versions, although you cannot see the flushing occuring in
this example.

#include <iostream.h>
int main()
{
cout<<"USING '\\n' ...\n";
cout<<"Line 1 \nLine 2 \nLine 3 \n";
cout<<"USING end ..."<< endl;
cout<< "Line 1" << endl << "Line 2" << endl << "Line 3" << endl;
return 0;
}

Output
USING '\n' ...
Line 1
Line 2
Line 3
USING end ...
Line 1
Line 2
Line 3

88
setw() and setfill() manipulators

setw manipulator sets the width of the filed assigned for the output.

The field width determines the minimum number of characters to be written in some output representations.
If the standard width of the representation is shorter than the field width, the representation is padded with
fill characters (using setfill).

setfill character is used in output insertion operations to fill spaces when results have to be padded to the
field width.

Syntax

setw([number_of_characters]);

setfill([character]);

Consider the example

#include <iostream.h>
    #include <iomanip.h>
int main()
{
cout<<"USING setw() ..............\n";
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type- I]...\n";


cout<< setfill('0');
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type-II]...\n";


cout<< setfill('-')<< setw(10) <<11<<"\n";
cout<< setfill('*')<< setw(10) <<2222<<"\n";
cout<< setfill('@')<< setw(10) <<33333<<"\n";
cout<< setfill('#')<< setw(10) <<4<<"\n";
return 0;
}

89
Output

USING setw() ..............


11
2222
33333
4
USING setw() & setfill() [type- I]...
0000000011
0000002222
0000033333
0000000004
USING setw() & setfill() [type-II]...
--------11
******2222
@@@@@33333
#########4

setf() and setprecision() manipulator

setprecision manipulator sets the total number of digits to be displayed, when floating point numbers are
printed.

Syntax

setprecision([number_of_digits]);

cout<<setprecision(5)<<1234.537;

// output will be : 1234.5

On the default floating-point notation, the precision field specifies the maximum number of meaningful
digits to display in total counting both those before and those after the decimal point. Notice that it is not a
minimum and therefore it does not pad the displayed number with trailing zeros if the number can be
displayed with less digits than the precision.

In both the fixed and scientific notations, the precision field specifies exactly how many digits to display
after the decimal point, even if this includes trailing decimal zeros. The number of digits before the decimal
point does not matter in this case.

Syntax

setf([flag_value],[field bitmask]);

field bitmask flag values

left, right or
adjustfield
internal

basefield dec, oct or hex

90
scientific or
floatfield
fixed

Consider the example

#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"USING fixed .......................\n";
cout.setf(ios::floatfield,ios::fixed);
cout<< setprecision(5)<<1234.537<< endl;

cout<<"USING scientific ..................\n";


cout.setf(ios::floatfield,ios::scientific);
cout<< setprecision(5)<<1234.537<< endl;
return 0;
}

Output

USING fixed .......................


1234.53700
USING scientific ..................
1234.5

Consider the example to illustrate base fields

#include <iostream.h>
#include <iomanip.h>
int main()
{
int num=10;

cout<<"Decimal value is :"<< num << endl;

cout.setf(ios::basefield,ios::oct);
cout<<"Octal value is :"<< num << endl;

cout.setf(ios::basefield,ios::hex);
cout<<"Hex value is :"<< num << endl;
return 0;
}

DETECTING THE END-OF-FILE

C++ provides a special function, eof( ), that returns nonzero (meaning TRUE) when there are no more data
to be read from an input file stream, and zero (meaning FALSE) otherwise.

91
Rules for using end-of-file (eof( )):
1.  Always test for the end-of-file condition before processing data
read from an input file stream.
     a.  use a priming input statement before starting the loop
     b.  repeat the input statement at the bottom of the loop body
2.  Use a while loop for getting data from an input file stream. 
A for loop is desirable only when you know the exact number of
data items in the file, which we do not know.

#include <iostream.h>
#include <fstream.h>
#include <assert.h>

int main(void)
{
     int data;           // file contains an undermined number of integer
values
     ifstream fin;     // declare stream variable name

     fin.open("myfile",ios::in);    // open file


     assert (!fin.fail( ));     
     fin >> data;        // get first number from the file (priming the input
statement)
                              // You must attempt to read info prior to an eof(
) test.
     while (!fin.eof( ))      //if not at end of file, continue reading numbers
     {
          cout<<data<<endl;    //print numbers to screen
          fin >> data;               //get next number from file
     }
     fin.close( );       //close file
     assert(!fin.fail( ));
     return 0;
}

The seekg(), seekp(), tellg() and tellp() Functions

In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp() functions. The
seekg() and tellg() functions allow you to set and examine the get_pointer, and the seekp() and tellp()
functions perform these operations on the put_pointer.The seekg() and tellg() functions are for input streams
(ifstream) and seekp() and tellp() functions are for output streams (ofstream). However, if you use them with
an fstream object then tellg() and tellp() return the same value. Also seekg() and seekp() work the same way
in an fstream object. The most common forms of these functions are :

istream & seekg(long);


seekg()
istream & seekg(long, seek_dir);

ofstream & seekp(long);


seekp()
ofstream & seekp(long, seek_dir);

92
tellg() long tellg()

tellp() long tellp()

The working of seekg() & seekp() and tellg() & tellp() is just the same except that seekg() and tellg() work
for ifstream objects and seekp() and tellp() work for ofstream objects. In the above table, seek_dir takes the
definition enum seek_dir { beg, cur, end};.

The seekg() or seekp(), when used according to Form 1, then it moves the get_pointer or put_pointer to an
absolute position. Here is an example:

ifstream fin;
ofstream fout;
: // file opening routine
fin.seekg(30); // will move the get_pointer (in ifstream) to byte
number 30 in the file
fout.seekp(30); // will move the put_pointer (in ofstream) to byte
number 30 in the file

When seekg() or seekp() function is used according to Form 2, then it moves the get_pointer or put_pointer
to a position relative to the current position, following the definition of seek_dir. Since, seek_dir is an
enumeration defined in the header file iostream.h, that has the following values:

ios::beg, // refers to the beginning of the file


ios::cur, // refers to the current position in the file
ios::end} // refers to the end of the file

Here is an example.

fin.seekg(30, ios::beg); // go to byte no. 30 from beginning of file


linked with fin
fin.seekg(-2, ios::cur); // back up 2 bytes from the current position of
get pointer
fin.seekg(0, ios::end); // go to the end of the file
fin.seekg(-4, ios::end); // backup 4 bytes from the end of the file

The functions tellg() and tellp() return the position, in terms of byte number, of put_pointer and get_pointer
respectively, in an output file and input file.

The get(), getline() and put() Functions

The functions get() and put() are byte-oriented. That is, get() will read a byte of data and put() will write a
byte of data. The get() has many forms, but the most commonly used version is shown here, along with put()
:

istream & get(char & ch) ;


ostream & put(char ch) ;

93
The get() function reads a single character from the associated stream and puts that value in ch. It returns a
reference to the stream. The put() writes the value of ch to the stream and returns a reference to the stream.

The following program displays the contents of a file on the screen. It uses the get() function :

/* C++ Sequential Input/Output Operations on Files */

#include<iostream.h>
#include<stdlib.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char fname[20], ch;
ifstream fin; // create an input stream
clrscr();

cout<<"Enter the name of the file: ";


cin.get(fname, 20);
cin.get(ch);

fin.open(fname, ios::in); // open file


if(!fin) // if fin stores zero i.e., false value
{
cout<<"Error occurred in opening the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(1);
}

while(fin) // fin will be 0 when eof is reached


{
fin.get(ch); // read a character
cout<<ch; // display the character
}

cout<<"\nPress any key to exit...\n";


fin.close();
getch();
}

ERROR HANDLING WITH FILES

Sometimes during file operations, errors may also creep in. For example, a file being opened for reading
might not exist. Or a file name used for a new file may already exist. Or an attempt could be made to read
past the end-of-file. Or such as invalid operation may be performed. There might not be enough space in the
disk for storing data.

To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-state' members
from the ios class that store the information on the status of a file that is being currently used. The current
state of the I/O system is held in an integer, in which the following flags are encoded :

94
Name Meaning

eofbit 1 when end-of-file is encountered, 0 otherwise.

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

badbit 1 when a fatal I/O error has occurred, 0 otherwise

goodbit 0 value

C++ Error Handling Functions

There are several error handling functions supported by class ios that help you read and process the status
recorded in a file stream.

Function Meaning

Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has
int bad() occurred. However, if it is zero (false value), it may be possible to recover from any other error
reported and continue operations.

Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns zero
int eof()
(false value).

int fail() Returns non-zero (true) when an input or output operation has failed.

Returns non-zero (true) if no error has occurred. This means, all the above functions are false. For
int good() example, if fin.good() is true, everything is okay with the stream named as fin and we can proceed
to perform I/O operations. When it returns zero, no further operations can be carried out.

clear() Resets the error state so that further operations can be attempted.

Following table lists these error handling functions and their meaning :

COMMAND LINE ARGUEMENTS

95
In Command line arguments application main() function will takes two arguments that is;
 argc
 argv

argc : argc is an integer type variable and it holds total number of arguments which is passed into main
function. It take Number of arguments in the command line including program name.

argv[] : argv[] is a char* type variable, which holds actual arguments which is passed to main function.
Compile and run CMD programs

Command line arguments are not compile and run like normal C++ programs, these programs are compile
and run on command prompt. To Compile and Link Command Line Program we need TCC Command.
 First open command prompt
 Follow you directory where your code saved.
 For compile -> C:/TC/BIN>TCC mycmd.cpp
 For run -> C:/TC/BIN>mycmd 10 20
 Explanation: Here mycmd is your program file name and TCC is a Command. In "mycmd 10 20"
statement we pass two arguments.
Example of Command Line Argument in C++

#include<iostream.h>

#include<conio.h>

void main(int argc, char* argv[])

int i;

clrscr();

cout<<"Total number of arguments: "<<argc;

for(i=0;i< argc;i++)

cout<<endl<< i;<<"argument: "<<argv[i];

getch();

}
Output
C:/TC/BIN>TCC mycmd.cpp

C:/TC/BIN>mycmd 10 20

Number of Arguments: 3

96
0 arguments c:/tc/bin/mycmd.exe

1 arguments: 10

2 arguments: 20

Note: In above output we passed two arguments but is show "Number of Arguments: 3" because argc take
Number of arguments in the command line including program name. So here two arguments and one
program name (mycmd.exe) total 3 arguments

UNIT V : TEMPLATES

Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you
can create a single function or a class to work with different data types using templates.

Templates are often used in larger codebase for the purpose of code reusability and flexibility of the
programs.

CLASS TEMPLATE

Sometimes, you need a class implementation that is same for all classes, only the data types used are
different.

Normally, you would need to create a different class for each data type OR create different member
variables and functions within a single class.

This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function
should be performed on all classes/functions.

However, class templates make it easy to reuse the same code for all data types.

How to declare a class template?

template <class T>

class className

... .. ...

public:

T var;

T someOperation(T arg);

... .. ...

97
};

In the above declaration, T is the template argument which is a placeholder for the data type used.Inside the
class body, a member variable var and a member function someOperation() are both of type T.

How to create a class template object?

To create a class template object, you need to define the data type inside a < > when creation.

className<dataType> classObject;

For example:

className<int> classObject;

className<float> classObject;

className<string> classObject;

Example : Simple calculator using Class template

Program to add, subtract, multiply and divide two numbers using class template

#include <iostream>
template <class T>
class Calculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

void displayResult()

98
{
cout << "Numbers are: " << num1 << " and " << num2 << "." <<
endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }


};

int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;


intCalc.displayResult();

cout << endl << "Float results:" << endl;


floatCalc.displayResult();

return 0;
}

Output

Int results:

Numbers are: 2 and 1.

99
Addition is: 3

Subtraction is: 1

Product is: 2

Division is: 2

Float results:

Numbers are: 2.4 and 1.2.

Addition is: 3.6

Subtraction is: 1.2

Product is: 2.88

Division is: 2

In the above program, a class template Calculator is declared.

The class contains two private members of type T: num1 & num2, and a constructor to initalize the
members.

It also contains public member functions to calculate the addition, subtraction, multiplication and division of
the numbers which return the value of data type defined by the user. Likewise, a function displayResult() to
display the final output to the screen.

In the main() function, two different Calculator objects intCalc and floatCalc are created for data


types: int and float respectively. The values are initialized using the constructor.

Notice we use <int> and <float> while creating the objects. These tell the compiler the data type used for the
class creation.

This creates a class definition each for int and float, which are then used accordingly.

Then, displayResult() of both objects is called which performs the Calculator operations and displays the
output.

100
Class template with multiple parameters

While creating templates, it is possible to specify more than one type. We can use more than one generic
data type in a class template. They are declared as a comma-separated list within the template as below:

Syntax:

template<class T1, class T2, ...>


class classname
{
...
...
};

// CPP program to illustrate

// Class template with multiple parameters

#include<iostream>

// Class template with two parameters

template<class T1, class T2>

class Test

        T1 a;

        T2 b;

    public:

        Test(T1 x, T2 y)

        {

            a = x;

            b = y;

        }

        void show()

        {

            cout << a << " and " << b << endl;

        }

};

// Main Function

101
int main()

    // instantiation with float and int type

    Test <float, int> test1 (1.23, 123);

    // instantiation with float and char type

    Test <int, char> test2 (100, 'W');

    test1.show();

    test2.show();

    return 0;

Output:
1.23 and 123
100 and W

Function Templates

A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single normal function can only
work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use function
overloading to create two functions with the required function declaration.

However, a better approach would be to use function templates because you can perform the same task
writing less and maintainable code.

How to declare a function template?

A function template starts with the keyword template followed by template parameter/s inside  < > which is
followed by function declaration.

template <class T>

T someFunction(T arg)

... .. ...

102
}

In the above code, T is a template argument that accepts different data types (int, float), and class is a
keyword.

You can also use keyword typename instead of class in the above example.

When, an argument of a data type is passed to someFunction( ), compiler generates a new version
of someFunction() for the given data type.

Example : Function Template to find the largest number

Program to display largest among two numbers using function templates.

// If two characters are passed to function template, character with larger


ASCII value is displayed.
#include <iostream>
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;

cout << "Enter two integers:\n";


cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";


cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";


cin >> c1 >> c2;

103
cout << Large(c1, c2) << " has larger ASCII value.";

return 0;
}

Output

Enter two integers:

10

10 is larger.

Enter two floating-point numbers:

12.4

10.2

12.4 is larger.

Enter two characters:

z has larger ASCII value.

In the above program, a function template Large() is defined that accepts two arguments n1 and n2 of data
type T. T signifies that argument can be of any data type.

Large() function returns the largest among the two arguments using a simple conditional operation.

Inside the main() function, variables of three different data types: int, float and char are declared. The


variables are then passed to the Large() function template as normal functions.

During run-time, when an integer is passed to the template function, compiler knows it has to generate
a Large() function to accept the int arguments and does so.

Similarly, when floating-point data and char data are passed, it knows the argument data types and generates
the Large() function accordingly.
104
This way, using only a single function template replaced three identical normal functions and made your
code maintainable.

NON-TYPE PARAMETERS
A template non-type parameter is a special type of parameter that does not substitute for a type, but is
instead replaced by a value. A non-type parameter can be any of the following:

 A value that has an integral type or enumeration


 A pointer or reference to a class object
 A pointer or reference to a function
 A pointer or reference to a class member function
 std::nullptr_t

In the following example, we create a non-dynamic (static) array class that uses both a type parameter and a
non-type parameter. The type parameter controls the data type of the static array, and the non-type parameter
controls how large the static array is.

#include <iostream>

template <class T, int size> // size is the non-type parameter


class StaticArray
{
private:
    // The non-type parameter controls the size of the array
    T m_array[size];

public:
    T* getArray();

    T& operator[](int index)


    {
        return m_array[index];
    }
};

// Showing how a function for a class with a non-type parameter is defined outside of the class
template <class T, int size>
T* StaticArray<T, size>::getArray()
{
    return m_array;
}

int main()
{
    // declare an integer array with room for 12 integers
    StaticArray<int, 12> intArray;

    // Fill it up in order, then print it backwards


    for (int count=0; count < 12; ++count)
        intArray[count] = count;

    for (int count=11; count >= 0; --count)


        std::cout << intArray[count] << " ";
    std::cout << '\n';

    // declare a double buffer with room for 4 doubles


    StaticArray<double, 4> doubleArray;

    for (int count=0; count < 4; ++count)


        doubleArray[count] = 4.4 + 0.1*count;

105
    for (int count=0; count < 4; ++count)
        std::cout << doubleArray[count] << ' ';

    return 0;
}

This code produces the following:


11 10 9 8 7 6 5 4 3 2 1 0
4.4 4.5 4.6 4.7

EXCEPTION HANDLING
One noteworthy thing about the above example is that we do not have to dynamically allocate the m_array
member variable! This is because for any given instance of the StaticArray class, size is actually constant.
For example, if you instantiate a StaticArray<int, 12>, the compiler replaces size with 12. Thus m_array is of
type int[12], which can be allocated statically.

This functionality is used by the standard library class std::array. When you allocate a std::array<int, 5>, the
int is a type parameter, and the 5 is a non-type parameter!

An exception is a problem that arises during the execution of a program. A C++ exception is a response to
an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch,and throw.

 throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
 catch − A program catches an exception with an exception handler at the place in a program where
you want to handle the problem. The catch keyword indicates the catching of an exception.
 try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows

try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in case your try block
raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throwstatement. The operand of the throw
statement determines a type for the exception and can be any expression and the type of the result of the
expression determines the type of exception thrown.

106
Following is an example of throwing an exception when dividing by zero condition occurs −
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions
The catch block following the try block catches any exception. You can specify what type of exception
you want to catch and this is determined by the exception declaration that appears in parentheses following
the keyword catch.
try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to specify that a catch block
should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the
parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we catch it in catch block.

#include <iostream>

double division(int a, int b) {

if( b == 0 ) {

throw "Division by zero condition!";

return (a/b);

int main () {

int x = 50;

int y = 0;

double z = 0;

try {

z = division(x, y);

cout << z << endl;

} catch (const char* msg) {

cerr << msg << endl;

107
}

return 0;

Because we are raising an exception of type const char*, so while catching this exception, we have to use
const char* in catch block. If we compile and run above code, this would produce the following result −
Division by zero condition!

C++ Standard Exceptions


C++ provides a list of standard exceptions defined in <exception> which we can use in our programs.
These are arranged in a parent-child class hierarchy shown below −

Here is the small description of each exception mentioned in the above hierarchy −

108
Sr.No Exception & Description

1
std::exception

An exception and parent class of all the standard C++ exceptions.

2 std::bad_alloc

This can be thrown by new.

3
std::bad_cast

This can be thrown by dynamic_cast.

4 std::bad_exception

This is useful device to handle unexpected exceptions in a C++ program.

5
std::bad_typeid

This can be thrown by typeid.

6 std::logic_error

An exception that theoretically can be detected by reading the code.

7
std::domain_error

This is an exception thrown when a mathematically invalid domain is used.

8 std::invalid_argument

This is thrown due to invalid arguments.

9
std::length_error

This is thrown when a too big std::string is created.

10 std::out_of_range

This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().

11
std::runtime_error

An exception that theoretically cannot be detected by reading the code.

12 std::overflow_error

This is thrown if a mathematical overflow occurs.

109
13
std::range_error
RETHROWING AN EXCEPTION
Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no
exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can
only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the
next catch block.
- Consider the following code :
#include <iostream>
using namespace std;
void MyHandler()
{
   try
   {
       throw “hello”;
   }
   catch (const char*)
   {
   cout <<”Caught exception inside MyHandler\n”;
   throw; //rethrow char* out of function
   }
}
int main()
{
   cout<< “Main start”;
   try
   {
       MyHandler();
   }
   catch(const char*)
   {
      cout <<”Caught exception inside Main\n”;
   }
       cout << “Main end”;
       return 0;
}
Output :
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end

Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();

110
CORE PRACTICAL IV - PROGRAMMING IN C++
1. Write a C++ program to create a class ARITHMETIC which consists of a FLOAT and an INTEGER
variable. Write member functions ADD(),SUB(), MUL(), DIV() to perform addition, subtraction,
multiplication, division respectively. Write a member function to get and display values.
2. Write a C++ program to create a class FLOAT that contains one float data member. Overload all the four
Arithmetic operators so that they operate on the object FLOAT.
3. Write a C++ program to create a class STRING. Write a Member Function to initialize, get and display
strings. Overload the operators ++ and == to concatenate two Strings and to compare two strings
respectively.
4. Write a C++ program to create class, which consists of EMPLOYEE Detail like E_Number, E_Name,
Department, Basic, Salary, Grade. Write a member function to get and display them. Derive a class PAY
from the above class and write a member function to calculate DA, HRA and PF depending on the grade.
5. Write a C++ program to create a class SHAPE which consists of two VIRTUAL FUNCTIONS
Calculate_Area() and Calculate_Perimeter() to calculate area and perimeter of various figures. Derive
three classes SQUARE, RECTANGLE, TRIANGE from class Shape and Calculate Area and Perimeter
of each class separately and display the result.
6. Write a C++ program using Function Overloading to read two Matrices of different Data Types such as
integers and floating point numbers. Find out the sum of the above two matrices separately and display
the sum of these arrays individually.
7. Write a program to convert an Infix Expression to Postfix Expression using Arrays.
8. Write a C++ program to create a class to implement the data structure STACK. Write a constructor to
initialize the TOP of the STACK. Write a member function PUSH() to insert an element and member
function POP() to delete an element. Check for overflow and underflow conditions.
9. Write a C++ program to check whether the given string is a palindrome or not using Pointers.
10. Write a C++ program to merge two files into a single file.

111
1. Write a C++ program to create a class ARITHMETIC which consists of a FLOAT and an
INTEGER variable. Write member functions ADD(),SUB(), MUL(), DIV() to perform addition,
subtraction, multiplication, division respectively. Write a member function to get and display values.

#include<iostream.h>
#include<conio.h>
class ARITHMETIC
{
float a ,ans;
int b;
public:
void add();
void sub();
void mul();
void div();
void in();
void out();
}op;
void main()
{
clrscr();
cout<<"ARITHMETIC OPERATIONS\n";
cout<<"*****INPUT*****\n";
op.in();
cout<<"*****OUTPUT*****\n";
op.out();
getch();
}
void ARITHMETIC::in()
{
cout<<"Enter the values :\n";
cout<<"FLOATING POINT VALUE (a):";
cin>>op.a;
cout<<"INTEGER VALUE (b) :";
cin>>op.b;
}

112
void ARITHMETIC::out()
{
cout<<"ADDITION\n";
op.add();
cout<<op.ans<<"\n";
cout<<"SUBTRACTION\n";
op.sub();
cout<<op.ans<<"\n";
cout<<"MULTIPLICATION\n";
op.mul();
cout<<op.ans<<"\n";
cout<<"DIVISION\n";
op.div();
cout<<op.ans<<"\n";
}
void ARITHMETIC::add()
{
op.ans=op.a + op.b;
}
void ARITHMETIC::sub()
{
op.ans=op.a - op.b;
}

void ARITHMETIC::mul()
{
op.ans=op.a * (float)op.b;
}

void ARITHMETIC::div()
{
op.ans=op.a / (float)op.b;
}

113
ARITHMETIC OPERATIONS
*****INPUT*****
Enter the values :
FLOATING POINT VALUE (a) : 4.3
INTEGER VALUE (b) : 7
*****OUTPUT*****
ADDITION
11.3
SUBTRACTION
-2.7
MULTIPLICATION
30.100002
DIVISION
0.614286

2. Write a C++ program to create a class FLOAT that contains one float data member. Overload all
the four Arithmetic operators so that they operate on the object FLOAT.
#include<iostream.h>
#include<conio.h>
class FLOAT
{
float no;
public:
void getd()
{
cout<<"\n ENTER A FLOATING NUMBER:";
cin>>no;
}
void putd()
{
cout<<"\n\n ANSWER :"<<no;
}
FLOAT operator+(FLOAT);
FLOAT operator-(FLOAT);
FLOAT operator*(FLOAT);

114
FLOAT operator/(FLOAT);
};

FLOAT FLOAT :: operator+(FLOAT a)


{
FLOAT temp;
temp.no=no+a.no;
return temp;
}

FLOAT FLOAT :: operator-(FLOAT b)


{
FLOAT temp;
temp.no=no-b.no;
return temp;
}
FLOAT FLOAT :: operator*(FLOAT b)
{
FLOAT temp;
temp.no=no*b.no;
return temp;
}

FLOAT FLOAT :: operator/(FLOAT b)


{
FLOAT temp;
temp.no=no/b.no;
return temp;
}

void main()
{
clrscr();
FLOAT a,b,c;
cout<<"**************INPUT**************\n";
a.getd();
b.getd();

115
cout<<"\n***********OUTPUT***************\n";
cout<<"\n Arithmetic operator overloading\n";
c=a+b;
cout<<"\n\t Addition is:\t\t";
c.putd();
c=a-b;
cout<<"\n\t Subtraction is:\t\t";
c.putd();
c=a*b;
cout<<"\n\t Multiplication is:\t\t";
c.putd();
c=a/b;
cout<<"\n\t Division is:\t\t";
c.putd();
getch();
}

**************INPUT**************
ENTER A FLOATING NUMBER : 4.5
ENTER A FLOATING NUMBER : 5.4
***********OUTPUT***************
Arithmetic operator overloading
Addition is :
ANSWER : 9.9
Subtraction is :
ANSWER : -0.9
Multiplication is :
ANSWER : 24.300001
Division is :
ANSWER : 0.833333

116
3. Write a C++ program to create a class STRING. Write a Member Function to initialize, get and
display stings. Overload the operators ++ and == to concatenate two Strings and to compare two
strings respectively.

#include<iostream.h>
#include<string.h>
#include<conio.h>
class CString
{
public:
char str[20];
public:
void get_string()
{
cout<<"\n Enter string:";
cin>>str;
}
void display()
{
cout<<str;
}
CString operator+(CString x)
{
CString s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
int operator==(CString&t);
};
int CString :: operator==(CString&t)
{
for(int i=0;str[i]!='_';i++)
{
for(int j=0;t.str[j]!='_';j++)

117
{
if(str[i]==t.str[j])
{
return 0;
} else
{
return 1;
}
}
} return 0;
}
void main()
{
CString str1,str2,str3;
int result=0;
clrscr();
cout<<"************INPUT************\n";
str1.get_string();
str2.get_string();
cout<<"\n***********OUTPUT************\n";
cout<<"\n\n First string is :\t";
str1.display();
cout<<"\n\n Second string is :\t";
str2.display();
cout<<"\n";
str3=str1+str2;
cout<<"\n\n concatenated string is :\t";
str3.display();
cout<<"\n The String Comparison result is:\n";
result=str1==str2;
if(result==0)
{
cout<<"\n both strings are Equal";
}
else
{
cout<<"\n both strings are not equal";

118
} getch();
}

************INPUT************
Enter string : Naresh
Enter string : Kumar
***********OUTPUT************

First string is : Naresh


Second string is : Kumar

Concatenated string is : NareshKumar


The String Comparison result is :

both strings are not equal

4. Write a C++ program to create class, which consists of EMPLOYEE Detail like E_Number,
E_Name, Department, Basic, Salary, Grade. Write a member function to get and display them. Derive
a class PAY from the above class and write a member function to calculate DA, HRA and PF
depending on the grade.
#include <iostream.h>
#include <conio.h>
class EMPLOYEE
{
public:
char name[40],depart[40],grade;
int num,salary;
public:
void ed_get();
void ed_dis();
};

class PAY : public EMPLOYEE


{

119
public:
int DA,HRA,PF;
public:
void calculate();
}emp;

void EMPLOYEE :: ed_get()


{
cout<<"*****INPUT*****\n";
cout<<"Enter the following details about the Employee\n\n";
cout<<"Employee Name : ";cin>>name;
cout<<"\nEmployee ID : ";cin>>num;
cout<<"\nDepartment : ";cin>>depart;
cout<<"\nBase Salary : ";cin>>salary;
cout<<"\nGrade(1-4) : ";cin>>grade;
}

void EMPLOYEE :: ed_dis()


{
clrscr();
cout<<"*************OUTPUT***************\n";
cout<<"----------EMPLOYEE DETAILS----------\n";
cout<<"Employee Name : "<<name;
cout<<"\nEmployee ID : "<<num;
cout<<"\nDepartment : "<<depart;
cout<<"\nBase Salary : "<<salary;
cout<<"\nGrade : "<<grade;
cout<<"\nDearness Allowance : "<<emp.DA;
cout<<"\nHouse Rent Allowance : "<<emp.HRA;
cout<<"\nProvision Fund : "<<emp.PF;
cout<<"\n---------------------------------------\n\n";
cout<<"\nGROSS SALARY : "<<(salary+emp.DA+emp.HRA+emp.PF);
}
void main()
{
clrscr();
cout<<"DA , HRA & PF CALCULATION\n";

120
emp.ed_get();
emp.calculate();
emp.ed_dis();
getch();
}

void PAY :: calculate()


{
switch(grade)
{
case 1 : {
DA = 0.20 * salary;
HRA = 0.10 * salary;
PF = 0.12 * salary;
}
break;

case 2 : {
DA = 0.30 * salary;
HRA = 0.20 * salary;
PF = 0.12 * salary;
}
break;
case 3 : {
DA = 0.40 * salary;
HRA = 0.40 * salary;
PF = 0.24 * salary;
}
break;
case 4 : {
DA = 0.50 * salary;
HRA = 0.50 * salary;
PF = 0.24 * salary;
}
break;
default : {

121
DA = 0.20 * salary;
HRA = 0.10 * salary;
PF = 0.12 * salary;
}break;
}
}

DA , HRA & PF CALCULATION


*****INPUT*****
Enter the following details about the Employee
Employee Name : Anmol
Employee ID : 007
Department : B.C.A
Base Salary : 20000
Grade(1-4) : 2
*************OUTPUT***************
----------EMPLOYEE DETAILS----------
Employee Name : Anmol
Employee ID : 007
Department : B.C.A
Base Salary : 20000
Grade : 2
Dearness Allowance : 4000
House Rent Allowance : 2000
Provision Fund : 2399
----------------------------------------------------
GROSS SALARY : 28399

5. Write a C++ program to create a class SHAPE which consists of two VIRTUAL FUNCTIONS
Calculate_Area() and Calculate_Perimeter() to calculate area and perimeter of various figures. Derive
three classes SQUARE, RECTANGLE, TRIANGE from class Shape and Calculate Area and
Perimeter of each class separately and display the result.
#include <iostream.h>
#include <conio.h>
class Shape

122
{
protected:
double x, y, z;
public:
void set_dim(double i=0, double j=0, double k=0)
{
x = i;
y = j;
z = k; }
virtual void calculate_area(void)
{
cout << "No area computation defined ";
cout << "for this class.\n";
}
virtual void calculate_perimeter(void)
{
cout << "No perimeter computation defined ";
cout << "for this class.\n";
}
};
class triangle : public Shape
{
public:
void calculate_area(void)
{
cout << "Triangle with height ";
cout << x << " and base " << y;
cout << " has an area of =";
cout << 0.5 * x * y << ".\n"; }
void calculate_perimeter(void)
{
cout << "Triangle with three sides ";
cout << x << " + " << y << " + " <<z;
cout << " has an perimeter of =";
cout << x + y + z << ".\n";
}
};

123
class square : public Shape
{
public:
void calculate_area(void)
{
cout << "Square with dimensions ";
cout << x << " x " << y;
cout << " has an area of =";
cout << x * y << ".\n";
}
void calculate_perimeter(void)
{
cout << "Square with dimension ";
cout << x ;
cout << " has an perimeter of =";
cout << 4 * x << ".\n";
}
};

class rectangle : public Shape {


public:
void calculate_area(void)
{
cout << "Rectangle with length ";
cout << x << " and breath " << y;
cout << " has an area of =";
cout << x * y<< ".\n";
}
void calculate_perimeter(void)
{
cout << "Rectangle with length ";
cout << x << " and breath " << y;
cout << " has an perimeter of =";
cout << 2 * (x + y)<<".\n";
}
};

124
void main()
{
double a,b,c;
clrscr();
Shape *p;
triangle t;
square s;
rectangle r;
cout<<"***************INPUT****************\n";
cout<<"Enter the a,b,c values\n";
cin>>a>>b>>c;
cout<<"***************OUTPUT***************\n";
p = &t;
p->set_dim(a,b,c);
p->calculate_area();
p->calculate_perimeter();
p = &s;
p->set_dim(a,b);
p->calculate_area();
p->calculate_perimeter();
p = &r;
p->set_dim(a,b);
p->calculate_area();
p->calculate_perimeter();
getch( );
}

***************INPUT****************
Enter the a,b,c values
10.2
5.6
4.5
***************OUTPUT*************
Triangle with height 10.2 and base 5.6 has an area of = 28.56
Triangle with three sides 10.2 + 5.6 + 4.5 has an perimeter of = 20.3.

125
Square with dimensions 10.2 x 5.6 has an area of = 57.12
Square with dimension 10.2 has an perimeter of = 40.8
Rectangle with length 10.2 and breath 5.6 has an area of = 57.12.
Rectangle with length 10.2 and breath 5.6 has an perimeter of =31.6.

6. Write a C++ program using Function Overloading to read two Matrices of different Data Types
such as integers and floating point numbers. Find out the sum of the above two matrices separately
and display the sum of these arrays individually.

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

void read_arr(int a[10][10] , int row , int col)


{
int i,j;
cout<<"\nEnter the A Matrix with Integer datas\n";
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
cout<<"Enter Element<<” [ "<<i<< ” ] ” << " [ "<<j<< " ] =";
cin>>a[i][j];
}
}
}

void read_arr(float b[10][10],int row,int col)


{
int i,j;
cout<<"\n Enter the B Matrix with float datas\n";
for(i=1;i<=row;i++)
{

126
for(j=1;j<=col;j++)
{
cout<<"Enter Element<<” [ "<<i<< ” ] ” << " [ "<<j<< " ] =";
cin>>b[i][j];
}
}
}

void add_arr(int m1[10][10] , float m2[10][10] , float m3[10][10], int row , int col)
{
int i,j;
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
m3[i][j] = (m1[i][j] + m2[i][j]);
}
}
}

void print_arr(float m3[10][10] , int row , int col)


{
int i,j;
cout<<"\n*************OUTPUT****************\n";
cout<<" The result matrix is \n";
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
cout<<"\t"<<m3[i][j];
}
cout<<"\n";
}
}

127
void main()
{
int m1[10][10],row,col;
float m2[10][10],m3[10][10];
clrscr();
cout<<"*************INPUT**************\n";
cout<<"Enter number of rows :";
cin>>row;
cout<<"Enter number of colomns :";
cin>>col;
read_arr(m1,row,col);
read_arr(m2,row,col);
add_arr(m1,m2,m3,row,col);
print_arr(m3,row,col);
getch();
}

*************INPUT**************
Enter number of rows : 2
Enter number of colomns : 2

Enter the A Matrix with Integer datas


Enter Element[1][1]= 10
Enter Element[1][2]= 20
Enter Element[2][1]= 30
Enter Element[2][2]= 40

Enter the B Matrix with float datas


Enter Element[1][1]= 5.5
Enter Element[1][2]= 7.5
Enter Element[2][1]= 6.5
Enter Element[2][2]= 4.5

*************OUTPUT****************
The result matrix is
15.5 27.5

128
36.5 44.5

7. Write a program to convert an Infix Expression to Postfix Expression using Arrays.


#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
int i=0,j=0;
char infix[25],postfix[25];
clrscr();
cout<<"*************INPUT**************\n";
cout<<"Enter the infix notation\n";
gets(infix);
cout<<"*************OUTPUT*************\n";
cout<<"\n The postfix notation\n";
while(infix[i])
{
if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/'||infix[i]=='(')
postfix[j++]=infix[i];
else if((infix[i]>='0'&&infix[i]<='9') || (infix[i]>='A'&&infix[i]<='z') ||
(infix[i]>='a'&&infix[i]>='a'&&infix[i]<='z'))
putch(infix[i]);
if(infix[i]==')')
{

129
postfix[j]='\0';
while(postfix[--j]!='(')
putch(postfix[j]);
}
i++;
} getch();
}
*************INPUT**************
Enter the infix notation
((a+b)*(c–d)))
*************OUTPUT*************
The postfix notation\n
ab+cd-*
8. Write a C++ program to create a class to implement the data structure STACK. Write a
constructor to initialize the TOP of the STACK. Write a member function PUSH() to insert an
element and member function POP() to delete an element. Check for overflow and underflow
conditions.

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

class STACK
{
int stk[50],top,item;
public:
void PUSH();
void POP();
void display();
STACK()
{
top=0;
}
};

int max = 0;

130
void STACK :: PUSH()
{
if(top>=max)
{
cout<<"Overflow ! Stack is full\n";
}
else
{
cout<<"Enter an element : ";
cin>>stk[top];
top++;
}
}
void STACK :: POP()
{
if(top>0)
{
item=stk[top-1];
cout<<"Deleted Element : "<<item;
top--;
}
else
{
cout<<"Underflow ! Stack is Empty";
}
}

void STACK :: display()


{
int i;
if(top==0)
{
cout<<"Underflow ! Stack is empty\n";
}
else
{
for(i=top-1;i>=0;i--)

131
{
cout<<" \n "<<stk[i];
}
}
}

void main()
{
clrscr();
class STACK s;
int ch = 0;
cout<<"\n**************INPUT****************\n";
cout<<"Enter the maximum number of elements : ";
cin>>max;
cout<<"\nSTACK OPERATIONS\n";
cout<<"\n1--> PUSH\n\n2--> POP\n\n3--> DISPLAY\n\n4--> EXIT\n";
cout<<"*****************OUTPUT***************\n";
while(ch!=4)
{
cout<<"\nEnter your choice : ";
cin>>ch;
switch(ch)
{
case 1 :s.PUSH();
break;
case 2 :s.POP();
break;
case 3 :s.display();
break;
case 4 : exit(1);
default : cout<<"Wrong options\n";
}
}
}

**************INPUT****************
Enter the maximum number of elements : 3

132
STACK OPERATIONS
1--> PUSH
2--> POP
3--> DISPLAY
4--> EXIT

*****************OUTPUT***************

Enter your choice : 1


Enter an element : 10

Enter your choice : 1


Enter an element : 20

Enter your choice : 1


Enter an element : 30

Enter your choice : 3


30
20
10
Enter your choice : 1
Overflow ! Stack is full

Enter your choice : 2


Deleted Element : 30
Enter your choice : 3

20
30
Enter your choice : 2
Deleted Element : 20
Enter your choice : 2
Deleted Element : 10
Enter your choice : 2
Underflow ! Stack is Empty
Enter your choice : 3

133
Underflow ! Stack is Empty

Enter your choice : 4

9. Write a C++ program to check whether the given string is a palindrome or not using Pointers.

#include<iostream.h>
#include<string.h>
#include<conio.h>
void main()
{
char string1[20];
int i,length;
int flag=0;
clrscr();
cout<<"\n*********INPUT***********\n";
cout<<"Enter the string:";
cin>>string1;
cout<<"\n*********OUTPUT**********\n";
strlwr(string1);
length=strlen(string1);
for(i=0;i<length;i++)
{

134
if(string1[i]!=string1[length-i-1])
{
flag=1;
break;
}
}
if(flag)
{
cout<<string1<<" is not a palindrome\n";
}
else
{
cout<<string1<<" is a palindrome\n";
}
getch();
}

*********INPUT***********
Enter the string: Madam
*********OUTPUT**********
madam is palindrome

*********INPUT***********
Enter the string: Welcome
*********OUTPUT**********
welcome is not palindrome

10. Write a C++ program to merge two files into a single file
#include<iostream.h>
#include<fstream.h>
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()

135
{
ifstream fin1,fin2;
ofstream fout;
char ch,file_name1[20],file_name2[20],file_name3[30];
clrscr();
cout<<"***************INPUT*****************\n";
cout<<"\n Enter first file name with Extension'.txt':";
gets(file_name1);
cout<<"\n Enter second file name with Extension'.txt:";
gets(file_name2);
cout<<"\n Enter third file name with Extension'.txt'";
cout<<"\n(Which will store the contents of first file and second file):";
gets(file_name3);
cout<<"***************OUTPUT*****************\n";
fin1.open(file_name1);
fin2.open(file_name2);

if(fin1==NULL||fin2==NULL)
{
cout<<"\n Invalid file name.\n There is no such file or directory....";
exit(EXIT_FAILURE);
}
fout.open(file_name3);
if(!fout)
{
cout<<"\n Invalid file name.\n There is no such file or directory....";
exit(EXIT_FAILURE);
}

while(fin1.eof()==0)
{
fin1>>ch;

136
fout<<ch;
}
while(fin2.eof()==0)
{
fin2>>ch;
fout<<ch;
}
cout<<"\n Two files have been merged into "<<file_name3<<" file successfully....!!!";
fin1.close();
fin2.close();
fout.close();
getch();
}

***************INPUT*****************
Enter first file name with Extension'.txt': file1.txt

Enter second file name with Extension'.txt:"; file2.txt

Enter third file name with Extension'.txt'


(Which will store the contents of\n first file and second file) : file3.txt
***************OUTPUT*****************
Two files have been merged into file3.txt file successfully....!!!"

137
138

You might also like