C++ Me
C++ Me
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
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 :
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
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
//LINKING SECTION
//DEFINITION SECTION
//MAIN FUNCTION
returntype main(arguements)
{
statement(s);
} //Definition of the main function
//SUB-PROGRAM SECTION
/*In this section the user-defined functions are defined */
6
DATA TYPES RANGE
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 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.
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
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
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.
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.
15
Flowchart:
Switch
expressi
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.
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:
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)
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
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.
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.
&& Called Logical AND operator. If both the operands are non-zero, then condition (A && B) is
becomes true. false.
! 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 −
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 −
& 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 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.
24
Assignment Operators
There are following assignment operators supported by C++ language
= 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
/= 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
25
Misc Operators
The following table lists some other operators that C++ supports.
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.
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.
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
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.
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.
int temp;
x = y; /* put y into x */
return;
For now, let us call the function swap() by passing values by reference as in the following example −
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
swap(a, b);
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;
}
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.
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() .
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.
#include <iostream.h>
class Geeks
public:
string geekname;
void printname()
{
}
};
int main() {
Geeks obj1;
obj1.geekname = "Abhi";
obj1.printname();
return 0;
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;
void printname();
void printid()
{
}
};
void Geeks::printname()
int main() {
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
obj1.printname();
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()
{
id=-1;
}
//Parametrized Constructor
Geeks(int x)
{
id=x;
}
};
36
int main() {
Geeks obj1;
Geeks obj2(21);
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;
~Geeks()
{
}
};
37
int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
return 0;
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
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.
1. For built in datatypes, returning a const or non-const value, doesn't make any difference.
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
}
5. But, a function which has a const type parameter, can be passed a const type argument as well as a non-
const 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.
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.
#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.
Output
42
Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
Both functions take single argument. However, one function takes integer as an argument and other takes
float as an argument.
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.
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; }
};
void show ()
{ cout<< "show derived class" <<endl; }
};
int main()
{
base *bptr;
derived d;
bptr = &d;
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;
#include <iostream.h>
class Box {
double width;
public:
};
width = wid;
int main() {
Box box;
box.setWidth(10.0);
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
#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
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:
// Constructor definition
length = l;
breadth = b;
height = h;
objectCount++;
double Volume() {
private:
};
int Box::objectCount = 0;
int main(void) {
return 0;
When the above code is compiled and executed, it produces the following result −
Constructor called.
49
Constructor called.
Total objects: 2
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:
// Constructor definition
length = l;
breadth = b;
height = h;
objectCount++;
double Volume() {
return objectCount;
private:
50
};
int Box::objectCount = 0;
int main(void) {
cout << "Inital Stage Count: " << Box::getCount() << endl;
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();
}
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;
}
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;
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:
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
length = l;
breadth = b;
height = h;
double Volume() {
private:
};
int main(void) {
ptrBox = &Box1;
56
cout << "Volume of Box1: " << ptrBox->Volume() << endl;
ptrBox = &Box2;
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
Operator Function
Example :
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(); }
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
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 :
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 :
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.
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.
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
#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.
#include <iostream.h>
//Base class
class Parent
public:
int id_p;
};
{ public:
int id_c; };
//main function
int main()
{
Child obj1;
62
obj1.id_c = 7;
obj1.id_p = 91;
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.
class A
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
63
// x is public
// y is protected
};
class C : protected A
// x is protected
// y is protected
};
// x is private
// y is private
};
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
};
// Single inheritance
#include <iostream.h>
// base class
class Vehicle {
public:
Vehicle()
};
};
// main function
int main()
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.
// multiple inheritance
#include <iostream.h>
class Vehicle {
public:
Vehicle()
{
}
};
class FourWheeler {
public:
FourWheeler()
{
66
cout << "This is a 4 wheeler Vehicle" << endl;
} };
};
// main function
int main()
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.
// Multilevel Inheritance
#include <iostream.h>
67
// base class
class Vehicle
public:
Vehicle()
{
}
};
{ public:
fourWheeler()
{
}
};
public:
car()
{
}
};
// main function
int main()
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.
// Hierarchical Inheritance
#include <iostream.h>
// base class
class Vehicle
public:
Vehicle()
{
}
};
};
};
69
// main function
int main()
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:
#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";
}
};
};
};
// main function
int main()
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.
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; }
};
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; }
};
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:
public:
width = a;
height = b;
int area() {
return 0;
};
public:
int area () {
};
public:
int area () {
};
int main() {
Shape *shape;
76
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
When the above code is compiled and executed, it produces the following result −
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 −
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.
#include <iostream.h>
int main () {
78
// access the value at the address available in pointer
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
#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) :
#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();
}
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 −
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.
1
ios::app
2 ios::ate
83
Open a file for output and move the read/write control to the end of the file.
3
ios::in
4 ios::out
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.
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];
ofstream outfile;
outfile.open("afile.dat”;
cin.getline(data, 100);
cin.ignore();
outfile.close();
ifstream infile;
infile.open("afile.dat”;
// again read the data from the file and display it.
85
cout << data << endl;
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.
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 −
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
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]);
#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";
89
Output
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;
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]);
left, right or
adjustfield
internal
90
scientific or
floatfield
fixed
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"USING fixed .......................\n";
cout.setf(ios::floatfield,ios::fixed);
cout<< setprecision(5)<<1234.537<< endl;
Output
#include <iostream.h>
#include <iomanip.h>
int main()
{
int num=10;
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;
}
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
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 :
92
tellg() long tellg()
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:
Here is an example.
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 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()
:
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 :
#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();
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
goodbit 0 value
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 :
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>
int i;
clrscr();
for(i=0;i< argc;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.
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.
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;
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;
}
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
return 0;
}
Output
Int results:
99
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Division is: 2
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.
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:
#include<iostream>
class Test
T1 a;
T2 b;
public:
Test(T1 x, T2 y)
{
a = x;
b = y;
}
void show()
{
}
};
// Main Function
101
int main()
test1.show();
test2.show();
return 0;
Output:
1.23 and 123
100 and W
Function Templates
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.
A function template starts with the keyword template followed by template parameter/s inside < > which is
followed by function declaration.
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.
When, an argument of a data type is passed to someFunction( ), compiler generates a new version
of someFunction() for the given data type.
103
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}
Output
10
10 is larger.
12.4
10.2
12.4 is larger.
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.
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:
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>
public:
T* getArray();
// 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;
105
for (int count=0; count < 4; ++count)
std::cout << doubleArray[count] << ' ';
return 0;
}
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>
if( b == 0 ) {
return (a/b);
int main () {
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
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!
Here is the small description of each exception mentioned in the above hierarchy −
108
Sr.No Exception & Description
1
std::exception
2 std::bad_alloc
3
std::bad_cast
4 std::bad_exception
5
std::bad_typeid
6 std::logic_error
7
std::domain_error
8 std::invalid_argument
9
std::length_error
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
12 std::overflow_error
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);
};
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************
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();
};
119
public:
int DA,HRA,PF;
public:
void calculate();
}emp;
120
emp.ed_get();
emp.calculate();
emp.ed_dis();
getch();
}
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;
}
}
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";
}
};
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>
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]);
}
}
}
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
*************OUTPUT****************
The result matrix is
15.5 27.5
128
36.5 44.5
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";
}
}
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***************
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
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
137
138