C++ Notes
C++ Notes
CONTENTS
● Introduction to C++
▪ Advantages
● I/O in C++
● C++ declarations
● Control Structures
▪ Loops in C++
● Inline functions
● Function overloading
INTRODUCTION TO C++
EVOLUTION OF C++
C++ is an object-oriented programming language and is considered to be an
extension of C. Bjarne Stroustrup at AT&T Bell Laboratories (USA) developed it in the
early 80s of 20th century. He wanted to combine the features of the languages Simula67
and C into a more powerful language that could support object-oriented programming.
The outcome was C++. Stroustrup called the new language ‘C with classes’. However, in
1983, the name was changed to C++. Rick Mascitti coined the term C++ in 1983.
Therefore, C++ is an extended version of C. C++ is a superset of C and all the concepts
of C are applicable to C++ also.
ANSI STANDARD
ANSI stands for American National Standard Institute. It was founded in 1918. The
main goal for establishing the institute is to suggest a standard for data processing in
USA. ANSI has made an international standard for C++.
Objects
Object is the basic unit and run time entity in object-oriented programming. Objects are
identified by its unique name. An object represents a particular instance of a class. There
can be more than one instance of a class. Each instance of a class can hold its own
relevant data. An Object is a collection of data members and associated member
functions also known as methods.
Classes
Classes are data types based on which objects are created. Objects with similar
properties and methods are grouped together to form a Class. Thus a Class represents a
set of individual objects. Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects become functions of the class
and are referred to as Methods.
Data Abstraction
Data abstraction refers to, providing only essential information to the outside word and
hiding their background details i.e. to represent the needed information in program
without presenting the details.
C++ classes provide great level of data abstraction. They provide sufficient public
methods to the outside world to play with the functionality of the object and to
manipulate object data without actually knowing how class has been implemented
internally.
Data Encapsulation
Data Encapsulation combines data and functions into a single unit called class. When
using Data Encapsulation, data is not accessed directly; it is only accessible through the
functions present inside the class. Data Encapsulation enables the important concept of
data hiding.
Inheritance
Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class. The new class that is formed
is called derived class. Derived class is also known as a child class or sub class.
Inheritance helps in reducing the overall code size of the program, which is an important
concept in object-oriented programming.
Polymorphism
Polymorphism is a term that indicates the ability to assume several shapes. In C++, it
allows more than one function to have the same name, but they differ in the arguments
passed. This is called function overloading. Thus the functions do different operations
though they have the same name. Similarly, operators can be made to do different
operation than what they do normally. This is called operator overloading.
Dynamic Binding
It refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call, at run time. It is associated with polymorphism and
inheritance.
Message Passing
In OOPS, objects communicate with each other. It includes the following steps
1. Declaring classes that define objects and their actions
2. Declaring objects from classes
3. Implementing relation between objects
Data is transferred from one object to another. A message for an object is a request for
execution of a procedure and it invoke a function in the receiving object that generates
the desired result. Message passing involves the following syntax.
Include Files
Class Declaration
A C++ program can have the structure shown above. It contains 4 parts namely:
1. Include Files
2. Class Declaration
3. Member function Definition
4. main() function
1. Include Files
C++ program depends upon some header files for function definition. Each header file
has an extension .h. The header file should be included using #include directive as
shown in the below example.
(Eg.)#include<iostream.h>
All the functions defined in the included header file are available in the current program.
The header files are included at the top the program, so that they can be accessible from
any part of the program.
2. Class Declaration
Declaration of the class is done in this section. It is also possible to declare class after
the main() function, but it is good practice to declare it before main() function. A class
contains data variables and prototypes of member functions or definitions of member
functions. The class definition is always terminated by a semicolon. Function prototype
declaration reports to the compiler about the function name, return type and arguments
type. Example of a function prototype is given below.
This function contains the definition of member functions. The function definition can be
done inside or outside the class. The functions defined inside the class are implemented
as inline functions. Normally very small functions are defined inside the class. When a
function is large, it is defined outside the class, using the scope resolution operator (::).
4. main() function
C++ programs always starts execution from main() function. This section contains the
declaration of objects, calling member functions of the objects and other statements.
Applications generally involve reading a large amount of data from input devices and
sending them to the output devices. Every language provides a set of built-in functions
for I/O operations. C++ has library functions to support I/O operation.
STREAMS IN C++
The C++ I/O functions make the user to work with different types of devices such as
keyboard, disk, tape drivers, etc. The stream is an intermediator between I/O devices
and the user. The standard C++ library contains the I/O stream functions.
cin Standard input, usually keyboard. It handles input from input devices
usually from keyboard
cout Standard output, usually screen. It passes data to output devices such as
monitor and printers
clog A fully buffered version of cerr. It controls error message that are passed
from buffer to the standard error device
cerr Standard error output, usually screen. It controls the unbuffered output
data. It passes errors to the monitor
C++ streams are based on class and object. C++ has a number of stream classes
that are used to work with console and file operations. These classes are known as
stream classes. All these classes are declared in the header file iostream.h. This file
must be included in the program if we are using functions of these classes.
The classes istream and ostream are derived classes of base class ios. The
class iostream is derived from the classes istream and ostream by using multiple
inheritance. The ios class has an ability to handle formatted and unformatted I/O
operations. The istream class supports both formatted and unformatted data. The
ostream class handles the formatting of output of data. The iostream contains
functioning of both istream and ostream classes.
Elements of the iostream library
Classes:
Base class with type-independent members for the standard stream
ios_base
classes
istringstrea
Input string stream class
m
ostringstrea
Output string stream class
m
stringstrea
Input/output string stream class
m
Objects:
cin Standard input stream
The data accepted or printed with default setting by the I/O function of the
language is known as unformatted data. For example, when cin statement is executed it
asks for a number. The user can enter an integer or floating point number based on the
data type declared.
The input stream uses cin object to read data and the output stream uses cout object to
display data on the screen. The cin and cout are predefined streams for input and output
of data. The data type is identified by the functions using the operators << and >>.
INPUT STREAM The input stream does read operation through keyboard. It uses cin as
object. The cin statement uses >> (extraction operator) before the variable name. The
cin statement is used to read data through the input device. The syntax is:
cin>>variable;
Example:
int v1;
float v2;
char v3;
cin>>v1>>v2>>v3;
For the above input, the operator will assign 100 to v1, 123.456 to v2 and A to v3. More
than one variable can be used in a single cin statement to input data. Such operations
are known as cascaded input operations. The input data is separated by space or enter.
Like scanf() statement in C, cin statement does not require control strings like %d for
integer, %f for float and so on.
OUTPUT STREAM The output stream does write operation to the monitor, the
standard output device. It uses cout as object. The cout statement uses << (insertion
operator) before the variable name. The syntax is:
cout<<variable;
Example:
int v1;
float v2;
char v3;
cin>>v1>>v2>>v3;
cout<<v1<<v2<<v3;
The cout statement in the above example will print the following output:
100 123.456 A
More than one variable can be used in a single cout statement to print data. Such
operations are known as cascaded output operations.
The following program will print the strings and character constants on the monitor.
P1.CPP
P1 OUTPUT
String = CMSCOLLEGE
character = D
Typecasting refers to the conversion of data from one basic type to another by applying
external use of data type keywords. The following program prints the data using
typecasting.
P2.CPP
P2 OUTPUT
integer in character format66 B
float in int format 2.5 2
double in character format 85.22 U
char in int format K 75
P3.CPP
//PRINTING ALPHABETS USING ASCII VALUES
//A TO Z 65-90, a to z 97-122
#include<iostream.h>
#include<conio.h>
void main()
{ int i;
clrscr();
for(i=65;i<=90;i++)
cout<<(char)i;
cout<<"\n";
for(i=97;i<=122;i++)
cout<<(char)i;
getch();
P3 OUTPUT
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
put() function
put() function is used to print a character on the monitor. This function is a member
function of iostream class. It is used with the cout object. The syntax is:
cout.put(c);
where ‘c’ is a character variable or a character constant. More than one put() function
can be used in a single cout statement in cascading style. The following program prints
the character constants using put() function.
P4.CPP
//PRINTING CHARACTER USING put() FUNCTION
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
cout.put('C');
cout.put('+');
cout.put('+');
cout<<"\n";
cout.put('C').put('P').put('P');
cout<<"\nBye";
getch();
P4 OUTPUT
C++
CPP
Bye
get() function
get() function is used to read a character from the keyboard. This function is a member
function of iostream class. It is used with the cin object. The syntax is:
cout.get(c);
where ‘c’ is a character variable. More than one get() function can be used in a single cin
statement in cascading style. The following program reads the characters and prints the
characters using get() and put() functions.
P5.CPP
P5 OUTPUT
cout.write(st,size);
Where ‘st’ is the string variable or string constant and ‘size’ is the size of the string. The
cout.write() statement displays only the specified number of characters given in the
second argument. If this argument value is more than the string length then blank space
is printed. The following program illustrates the usage of write() function.
P6.CPP
INDIA IS GREAT
NEW
Bye
read() function
This function is used to read the string from the keyboard. This function is used with cin
object. The syntax is
cin.read(st,size);
Where ‘st’ is the string variable and ‘size’ is the size of the string. When we use read
statement it is necessary to enter characters equal to the number specified in the
argument. This function continues to read characters till the number of characters
entered is equal to the size specified. The following program illustrates the usage of
read() function.
P7.CPP
P7 OUTPUT
getline() function
This function is used to read one or more strings from the keyboard. This function is used
with cin object. It reads the string including white space. The input reading is terminated
when user enter presses enter key. The syntax is given below.
getline(st, size);
where ‘st’ is the string variable and ‘size’ is the size of the string variable. It is not
necessary to enter number of characters specified in ‘size’ argument. When the user
presses the enter key, reading input is terminated. When the user enters more number
of characters than the size specified in the argument, only ‘size’-1 characters are read.
P8.CPP
P8 OUTPUT
P9.CPP
Enter a line
i love my country
i
i
il
i lo
i lov
i love
i love
i love m
i love my
i love my
i love my c
i love my co
i love my cou
i love my coun
i love my count
i love my countr
i love my country
Bye
peek() function
This function reads and returns the next character without extracting it, i.e. leaving it as
the next character to be extracted from the stream.
ignore() function
This function extracts characters from the input sequence and discards them .
P10.CPP
//PRINTING STRINGS USING peek() and ignore() FUNCTIONS
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{ char c;
clrscr();
cout<<"Enter text (Press F6 to end) : ";
while(cin.get(c))
{ cout<<c;
while (cin.peek()=='#')
cin.ignore(1,'#');
}
cout<<"\nBye";
getch();
}
P10 OUTPUT
putback() function
This function replaces the given character into the input stream
P11.CPP
P11 OUTPUT
gcount() function
This function returns the number of unformatted characters extracted from input stream.
P12.CPP
P12 OUTPUT
The functions available in the ios class for formatting the output are:
Function Operation
width() Sets the required field width
precision() Sets the no. of digits to be displayed after decimal point
fill() Sets the character to fill the black spaces of a field
setf() Sets the various flags for formatting output
unsetf() Removes the flag setting
P13.CPP
P13 OUTPUT
3.14
3.1
3.14
3.143
3.1429
3.14286
3.142857
3.1428571
3.14285707
3.142857075
3.1428570747
P14.CPP
getch();
}
P14 OUTPUT
123.456
*******ABC
+++++++++++++++++XYZ
cout.setf(flag1, flag2);
The unsetf() function in the ios class is used to clear the flags that was set. The syntax
is:
cout.unsetf(flag);
P15.CPP
P.15 OUTPUT
ABC*******
XYZ+++++++++++++++++
-----------------IJK
P16.CPP
P.16 OUTPUT
1.23456e+02
9.87e-03
c
13
cout.setf(flag);
P.17 OUTPUT
+123
+56.78
+56.780000
0xf
+1.234560e+02
0XF
+1.234560E+02
BUILT-IN MANIPULATORS
Built-In Manipulators available in iomanip.h header file can be used for printing the
formatted output. Some of the manipulators are given below.
Manipulator Operation
setw() Sets the field width
setbase() Sets the specified base for numbers
setprecision() Sets the number of digits to display after decimal point
setfill() Sets the character to be filled in blank spaces of the field
endl Creates a new line (similar to ‘\n’)
Hex, oct, dec Displays number in hexadecimal, octal, decimal base
P18.CPP
P.18 OUTPUT
Hello
12.35
+++++++Bye
20
10
16
P19.CPP
void main()
{ clrscr();
cout<<100<<T<<200<<T<<300;
cout<<B;
getch();
}
P.19 OUTPUT
100 200 300
BYE
C++ DECLARATIONS
TOKENS
A token is the smallest unit, which is a group of characters that logically belong together.
The programmer can write a program by using tokens. C++ uses the following types of
tokens.
Keywords, Identifiers, Literals, Punctuators, Operators.
1. Keywords
These are some reserved words in C++ which have predefined meaning to compiler
called keywords. Some commonly used Keywords are given below:
2. Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a
sequence of characters taken from C++ character set. The rules for the formation of an
identifier are:
3. Literals
Literals (often referred to as constants) are data items that never change their value
during the execution of the program. The following types of literals are available in C++.
● Integer-Constants
● Character-constants
● Floating-constants
● Strings-constants
Integer Constants
Integer constants are whole number without any fractional part. C++ allows three types
of integer constants.
Decimal integer constants: It consists of sequence of digits and should not begin with
0 (zero). For example 124, - 179, +108.
Octal integer constants: It consists of sequence of digits starting with 0 (zero). For
example 014, 012.
Character constants
A character constant in C++ must contain one or more characters and must be enclosed
in single quotation marks. For example 'A', '9', etc. C++ allows non-graphic characters
which cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc.
These characters can be represented by using an escape sequence. An escape sequence
represents a single character. The following table gives a listing of common escape
sequences.
Floating constants
They are also called real constants. They are numbers having fractional parts. They may
be written in fractional form or exponent form. A real constant in fractional form consists
of signed or unsigned digits including a decimal point between digits. For example 3.0, -
17.0, -0.627 etc.
String Literals
A sequence of character enclosed within double quotes is called a string literal. String
literal is by default (automatically) added with a special character ‘\0' which denotes the
end of the string. Therefore the size of the string is increased by one character. For
example "COMPUTER" will re represented as "COMPUTER\0" in the memory and its size is
9 characters.
4. Punctuators
5. Operators
Operators are special symbols used for specific purposes. C++ provides six types of
operators. Arithmetic operators, Relational operators, Logical operators, Bitwise
operators, Unary operators, Increment and Decrement operators, Assignment operator,
Conditional operators and Special operators.
Arithmetical operators
Relational operators
The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational
expression returns zero when the relation is false and a non-zero when it is true. The
following table shows the relational operators.
Logical operators
The logical operators are used to combine one or more relational expression. The logical
operators are
Operators Meaning
|| OR
&& AND
! NOT
Bitwise operators
Symb
Operator Form Operation
ol
x <<
left shift << all bits in x shifted left y bits
y
x >> all bits in x shifted right y
right shift >>
y bits
bitwise
~ ~x all bits in x flipped
NOT
bitwise each bit in x AND each bit in
& x&y
AND y
bitwise OR | x|y each bit in x OR each bit in y
bitwise each bit in x XOR each bit in
^ x^y
XOR y
Unary operators
C++ provides two unary operators for which only one variable/value is required.
For Example a = - 50; a = + 50; Here plus sign (+) and minus sign (-) are unary
because they are not used between two variables/values.
C++ provides two special operators viz '++' and '--' for incrementing and decrementing
the value of a variable by 1. The increment/decrement operator can be used with any
type of variable but it cannot be used with any constant. Increment and decrement
operators each have two forms, pre and post.
Pre-increment: ++variable
Post-increment: variable++
Pre-decrement: ––variable
Post-decrement: variable––
int x,y;
int i=10,j=10;
x=++i; //add one to i, store the result back in x
y=j++; //store the value of j to y then add one to j
cout<<x; //11
cout<<y; //10
Assignment operator
The assignment operator '=' is used for assigning a variable to a value. This operator
takes the expression on its right-hand-side and places it into the variable on its left-hand-
side. For example: m = 5; The operator takes the expression on the right, 5, and stores it
in the variable on the left, m. x = y = z = 32; This code stores the value 32 in each of the
three variables x, y, and z.
in addition to standard assignment operator shown above, C++ also support compound
assignment operators.
Conditional operator
The conditional operator ?: is called ternary operator as it requires three operands. The
format of the conditional operator is:
If the value of conditional expression is true then the expression1 is evaluated, otherwise
expression2 is evaluated. int a = 5, b = 6;
big = (a > b) ? a : b; The condition evaluates to false, therefore biggest the value from b
and it becomes 6.
Special Operators
Conditional operator C++ provides two special operators known as sizeof operator and
comma operator.
The comma operator gives left to right evaluation of expressions. When the set of
expressions has to be evaluated for a value, only the rightmost expression is considered.
int a=1, b=2, c=3, i; // comma acts as separator, not as an operator
i = (a, b); // stores b into i Would first assign the value of a to i, and then assign value of
b to variable i. So, at the end, variable i would contain the value 2.
As we know that different types of variables, constants, etc. require different amounts of
memory to store them, the sizeof operator can be used to find how many bytes are
required for an object to store in memory.
For example sizeof (char) returns 1, sizeof (int) returns 2, sizeof (float) returns 4. If k is
integer variable, the sizeof (k) returns 2.
The sizeof operator determines the amount of memory required for an object at compile
time rather than at run time.
Operator Description
<< Insertion operator
>> Extraction operator
:: Scope resolution ( or access) operator
::* Pointer to member decelerator
->* Pointer to member operator
.* Pointer to member operator
delete Memory release operator
new Memory allocation operator
PRECEDENCE OF OPERATORS
The order in which the Arithmetic operators (+,-,*,/,%) are used in a. given expression is
called the order of precedence. The following table shows the order of precedence.
Order Operators
First ()
Second *, /, %
Third +, -
C++ supports a large number of data types. The built- in or basic data types supported
by C++ are integer, floating point and character. These are summarized in table along
with description and memory requirement.
Arrays
Array is a collection of elements of similar data types in which each element is located in
separate memory location. It shares a common name and each element can be accessed
using subscript.
Eg. int a[5];
Functions
Function is a block of statements that perform a special task when called. In C++, more
than one function can have the same name, which is called function overloading.
Pointers
Pointer is a variable used to store the address of a memory location. The address
assigned to a variable can be stored in a pointer variable, using the address operator
(&). Pointer variable should be declared using the operator ‘*’. Consider the following
example.
int *p, a;
p=&a;
In the above segment, p is a pointer variable, which is used to store the address of the
variable ‘a’.
References
The ‘&’ operator can be used to declare alias for variables and the user can use the
variable by reference. Consider the following example.
Int p=10;
Int & q=p;
Here ‘p’ is already declared and initialized. The second statement defines an alternative
variable name (alias) ‘q’ to variable ‘p’. Both the variables point the same data. The
changes made in one variable causes changes in the other variable also.
q=q*2;
Structures
Structure is used to combine variables of different types into single variable. The
members of the structure variables can be accessed using the member operator (.). The
syntax for declaring structure variable is:
The tag name can be used to create required number of structure variables. The
following example illustrates this.
struct stud
{ int roll,
float avg;
};
struct s1,s2,s3;
Classes
Class is a new concept introduced in C++. The syntax is similar to structure. Class is
combination of variables, called data members and functions, called member functions,
which uses those data members. The structure of a class is shown below.
void fun(void);
The above prototype informs the compiler that the function fun does not return any
value and no argument is passed to this function.
VARIABLES
It is a location in the computer memory which can store data and is given a symbolic
name for easy reference. The variables can be used to hold different values at different
times during the execution of a program.
In this statement a value 20.00 has been stored in a memory location Total.
Declaration of a variable
Before a variable is used in a program, we must declare it. This activity enables the
compiler to make available the appropriate type of location in the memory.
You can declare more than one variable of same type in a single statement.
eg. int x,y;
Initialization of variable
When we declare a variable its default value is undetermined. We can declare a variable
with some initial value.
eg. int a = 20;
The scope access (or resolution) operator is used to access the global version of a
variable. The same variable can be declared in many blocks, in a program. The block
which contains the declaration of the variable can access that variable. But the global
version of that variable can be accessed by any block using the (::) operator. Consider
the following example.
#include<iostream.h>
#include<conio.h>
int a=10;
void main()
{int a = 20;
cout<<”::a=”<<::a;
cout<<” a=”<<a;
}
The first cout statement prints the global version of ‘a’, whose value is 10. The second
cout statement prints the local version of ‘a’, whose value is 20.
CONTROL STRUCTURES
A Program is a sequence of statements that are executed one after the other.
Sometimes the programmer may need to alter the flow of execution, or to perform the
same operation for fixed iterations or whenever the condition does not satisfy. In such a
situation the programmer uses the control structure. The control structures can be
classified into two categories, namely decision making statements and decision making
statements.
The decision making statements are also known as branching statements, since they
branch (or transfer) the control from one location to another. The following decision
making statements are available in C++.
1. if
2. if-else
3. goto
4. break
5. continue
6. switch
if statement
This branching statement is used when one or more statements are to be executed only
when a condition is satisfied. The syntax of if statement is given below.
if (condition)
{ statement 1;
statement 2;
.
.
statement n;
}
The statements in the block, next to the condition are executed, if the condition is true,
else it is skipped. The following program uses if statement, to find the greater among
two numbers.
P20.CPP
#include<iostream.h>
#include<conio.h>
void main()
{ int a,b;
clrscr();
cout<<"Enter two numbers : ";
cin>>a>>b;
if(a>b)
cout<<"\n"<<a<<" is greater";
if(b>a)
cout<<"\n"<<b<<" is greater";
getch();
}
P20.OUTPUT
Enter two numbers : 100 200
200 is greater
P20.OUTPUT
Enter two numbers : 200 100
200 is greater
if-else statement
This branching statement is used when one set of statements are to be executed when a
condition is true and another set of statements are to be executed when the condition is
false. The syntax of if-else statement is given below.
if (condition)
{ true block statements
}
else
{ false block statements
}
If the condition is true, the statements in the true block will be executed, else statements
in the false block will be executed. The following program uses if-else statement to find
the greater among two numbers.
P21.CPP
#include<iostream.h>
#include<conio.h>
void main()
{ int a,b;
clrscr();
cout<<"Enter two numbers : ";
cin>>a>>b;
if(a>b)
cout<<"\n"<<a<<" is greater";
else
cout<<"\n"<<b<<" is greater";
getch();
}
P21.OUTPUT
2000 is greater
P21.OUTPUT
Enter two numbers : 2000 1000
2000 is greater
Jump statement
C++ has four statements that perform an unconditional control transfer. They can be
called as jump statements. They are return, goto, break and continue. Among these
return statement is used only in functions. The goto statement can be used anywhere in
the program. But break and continue statements are used in loops.
goto statement
This statement does not require any condition. This statement transfers the control from
a location to any location in the program. This statement can be also used with
condition, i.e. the control is transferred only when a condition is satisfied. The syntax of
goto statement is given below.
goto label;
.
label: _ _ _
break statement
The break statement transfers the control from inside a block to outside the block. This
statement is mostly used in switch statement. It can be also used in loop statements,
which terminates the continuation of the loop iteration.
continue statement
The continue statement is used in loop statements, especially in for loop. When this
statement is executed, the statements after it, in the loop are skipped and the next
iteration is continued. The following example illustrates the function of continue
statement.
P22.CPP
//PRINTING NUMBERS USING CONTINUE STATEMENT
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
for(int i=1;i<=20;i++)
{ if(i%2==0)
continue;
cout<<" "<<i;
}
getch();
}
P22.OUTPUT
1 3 5 7 9 11 13 15 17 19
switch statement
Switch is multi-way decision statement. if and if/else statements can become quite
confusing when nested too deeply, and C++ offers an alternative, called switch
statement. Unlike if, which evaluates one value, switch statements allow you to branch
on any of a number of different values. The general form of the switch statement is:
switch (exp)
{
case valueOne: statement;
break;
case valueTwo: statement;
break;
....
case valueN: statement;
break;
default: statement;
}
exp is any legal C++ expression, and the statements are any legal C++ statements or
block of statements. switch evaluates expression and compares the result to each of
the case values. When there is a match between expression value and case value, the
block associated with that is executed. If the expression is a character constant or
variable, then the character values against case should be enclosed within single quotes.
The break statement is used to stop execution and transfer control to the statement
after the switch block. Without a break statement, every statement from the matched
case label to the end of the switch, including the default, is executed. Consider the
following segment.
switch (choice)
{
case 0:
cout << "Zero!" << endl;
break;
case 1:
cout << "One!" << endl;
break;
case 2:
cout << "Two!" << endl;
break;
default:
cout << "Default!" << endl;
}
The above segment will produce the following output for the respective input.
Input Output
Choice = 0 Zero
Choice = 1 One
Choice = 2 Two
Choice = other Default
than 0,1 and 3
Loops in C++
Sometimes it may be necessary to execute certain statements more than one time. Loop
structures can be used to execute such statements iteratively or repeatedly. C++
provides loop structures, such as for, while and do-while.
for loop
This loop is used to repeat execution for a set of statements, for a specific number of
times. Hence this loop can be used if the number of iterations is known in advance. The
syntax of for loop is given below.
In the above syntax, ‘exp1’ is the initialization expression, which initializes a counter
variable. The second expression ‘exp2’ is a relative expression which is used to
terminate the iteration of the loop. The body of the loop is executed repeatedly while this
expression (or condition) is true. The ‘exp3’ is an arithmetic expression, which
increments the counter variable after every iteration of the loop. There may be more
than one exp1, exp2 or exp3 in a for loop. The ‘exp1’ is executed only once when the
control is entered to the loop structure. This loop is called as an ‘entry-controlled’ loop,
since the execution of the body of the loop is started only if the condition is true in the
beginning itself. The following demonstrates the usage of for loop.
P23.CPP
P23.OUTPUT
1 3 5 7 9 11 13 15 17 19
while loop
This is another ‘entry-controlled’ loop structure available in C++. This loop is used when
a set of statement to be executed while a condition is true. The syntax of while loop is
given below.
while(condition)
The condition is a relational expression, which is evaluated when the control is entered
the loop structure. The iteration is started only if the condition is true. The following
program demonstrates the usage of while loop.
P24.CPP
1 3 5 7 9 11 13 15 17 19
do-while loop
This is an ‘exit-controlled’ loop structure available in C++. Like while loop, this loop is
used when a set of statement to be executed while a condition is true. The syntax of do-
while loop is given below.
do
} while(condition);
The body of the loop is executed for the first time and the condition is tested. If the
condition is true, the next iteration is continued. Hence the body of the loop is executed
for the first time even if the condition is false. Only for the second and remaining
iterations, the condition should be true. The following program demonstrates the usage
of d0-while loop.
P25.CPP
P25.OUTPUT
1 3 5 7 9 11 13 15 17 19
INLINE FUNCTIONS
A function is a set of statements which will be doing a specific task. The main objective
of using functions is to save memory space. When a specific task has to be repeated for
many times, the respective function can be called. However, every time a function is
called, a lot of time is consumed in saving return address into stack, changing program
counter value and retrieving return address from stack. This time consumption can be
avoided by using inline functions.
The inline functions works like a macro. Whenever a macro is executed, it is replaced
with its value, in the statement. Similarly, whenever an inline function is called, the call
is replaced with its definition and no control is transferred to function definition. The
structure of inline function is given below.
However, for the following situations the inline function may not work.
1. For functions containing loop, switch or goto
2. For functions containing static variable
3. For functions which are recursive
4. For main function
P26.CPP
void main()
{
clrscr();
cout<<mul(10,2)<<endl;
cout<<div(10,3)<<endl;
getch();
}
P26.OUTPUT
20
3.333333
FUNCTION OVERLOADING
There is a provision for using more than one function with same name in a C++
program. This provision is called function overloading, which is a type of polymorphism.
However, each function should have different number of arguments or arguments of
different data types. The following program demonstrates the use of function
overloading.
P27.CPP
float area(double r)
{ return(22.0/7*r*r);
}
P27.OUTPUT
CONTENTS
▪ Declaring Objects
▪ Array of Objects
▪ Friend Functions
In C++, structures are allowed to contain functions and variables. This new data type is
called class. The class provides a facility to hide the data, i.e. a programmer can decide
whether a data can be accessed or not, directly. This mechanism of restricting access to
data from outside the class is called as data hiding or encapsulation. The syntax of a
class definition is similar to structure defining, except that the keyword ‘struct’ is
replaced with the keyword ‘class’.
The variables in a class are called as member variables or data members. The
functions in the class are called as member functions. The general form of a class
declaration is:
class class_name
{
private:
Variable declarations;
Function declarations;
public:
Variable declarations;
Function declarations;
};
Declaring Objects
A class is declared only to build the structure of objects. Objects are created using
classes. The declaration of objects is same as declaration of any variables of basic data
types. Defining objects of class type is known as class instantiation. When objects are
created, only during that moment, memory is allocated to them.
Classes are used to create objects and the members of the objects are accessed using
the dot (.) operator. The class members (variables and functions) declared under
private section cannot be accessed from outside the class, i.e. by the main function.
The class members declared under public section can be accessed from outside the
class. The keywords private and public are called as visibility labels or access
specifiers. The access specifier protected is used in base class and derived class,
which uses the concept of inheritance and discussed later in this book.
The following program illustrates the usage of access specifiers. The members of a class
declared without any access specifiers are considered as private members, i.e. the
default visibility of the members is private.
P28.CPP
//PROGRAM TO DEMONSTRATE THE USE OF ACCESS SPECIFIERS
#include<iostream.h>
#include<conio.h>
class test
{ private:
int a;
void prifun()
{ cout<<"\nPrivate function";
}
public:
int b;
void pubfun()
{ cout<<"\nPublic function";
}
};
void main()
{ test x;
clrscr();
x.a=10; // a is not accessible
x.b=20;
x.prifun(); // prifun is not accessible
x.pubfun();
getch();
}
When the program is executed, the compiler will show errors at the commented
statements, which should be removed for execution. The removal of commented
statements will produce the following output.
P28.OUTPUT
Public function
The private members (variables and functions) can be accessed by any other member
functions declared in the same class. The following program demonstrates this.
P29.CPP
//PROGRAM TO ACCESS THE PRIVATE MEMBERS
#include<iostream.h>
#include<conio.h>
class test
{ private:
int a;
void prifun()
{ cout<<"\nPrivate function";
}
public:
int b;
void pubfun()
{ a=100;
cout<<a;
prifun();
cout<<"\nPublic function";
}
};
void main()
{ test x;
clrscr();
x.pubfun();
getch();
}
In the above program, the public function ‘pubfun’ access the private members ‘a’ and
‘prifun’ and the following output is produced.
P29.OUTPUT
100
Private function
Public function
The member functions can be defined in private or public section, by using any of the
following two methods.
P30.CPP
void main()
{ bill x;
clrscr();
x.value();
x.show();
getch();
}
P30.OUTPUT
Item code = 101
Item rate = 250
The member functions can be defined outside the class also. But the prototype
declaration of those functions should be inside the class. The prototype may be in
private or public section. The member functions are defined using the scope resolution
operator. The function header should have the following syntax, for defining the function
outside the class.
P31.CPP
P31.OUTPUT
Item code = 101
Item rate = 250
When objects are created, memory is allocated to data members of each object
separately, i.e. the objects have their own set of data members. But each object will not
have their own functions. In other words, memory is not allocated to member function of
each object separately. Memory is allocated to only one member function and all objects
will share that common member function. Similarly, when a member variable is declared
as static, only one copy of that variable is created and all objects will share that variable.
The following program illustrates the difference between static member variable and
non-static member variable.
P32.CPP
In the above program, ‘a’ is non-static variable and ‘s’ is static variable. The static
variable ‘s’ is initialized to 0, outside the class using the scope resolution operator. The x,
y and z objects call the init() function to initialize their non-static variable ‘a’ to zero. The
three objects call the incr() function to increment the static variable ‘s’ to 1, 2 and 3. The
above will produce the following output.
P32.OUTPUT
a= 1
s= 1
a= 1
s= 2
a= 1
s= 3
Static Member Functions
Like member variables, functions can be also declared as static. The static member
functions can access only static member variables and functions of the same class. The
non-static members cannot be accessed by static member functions. The static member
function declared in public section can be called using its class name, without using the
object. The following program illustrates the use of static member function.
P33.CPP
P33.OUTPUT
s=0
s=1
s=2
Static member function can be also declared in private section. The private static
function can be called by public static function. The following program illustrates this.
P34.CPP
P34.OUTPUT
s=1
s=2
s=3
We have already mentioned that the public static member function can be called from
main function, using the following syntax.
Class_name::static_member_function
();
Similarly, public static member variable can be accessed from main function, using the
following syntax.
Class_name::static_member_variable;
The following illustrates the use of public static member variable, global and local
variables.
P35.CPP
P35.OUTPUT
Global variable v = 11
Class variable v = 22
Local variable v = 33
Array of objects
Array is a collection of variables of similar data type. Similarly objects of same class can
be declared as array. The array elements of basic data types can be accessed using the
array subscript. Similarly, the individual object in an array of objects can be accessed
using the subscript. The following program prints whether the number is positive or
negative, using array of objects.
P36.CPP
P36.OUTPUT
Enter a no : 100
Positive
Enter a no : -50
Negative
Enter a no : 200
Positive
Enter a no : -75
Negative
Enter a no : 350
Positive
Friend Functions
The very basic concept of OOPS is to provide data security. This is achieved by data
hiding and encapsulation. When data members are declared in the private section of the
class, they cannot be accessed by non-member functions. This restriction becomes a
bottleneck in some programming situations.
Consider a function that has to operate on two objects of different classes. It is only a
function that is unfamiliar to both classes can do this job. Since a function cannot be
defined in both the classes, this can be done by a friend function. A friend function must
be declared by placing the keyword friend before the function name. A friend may be
declared or defined within the scope of a class definition.
A function can be friend to many classes. The following points may be noted about friend
functions.
1. A friend function may be declared either in the private or public section of the
class.
2. A friend function may be defined inside or outside the class.
3. The scope of a friend function is restricted to the class in which it has declared as
a friend.
4. A friend function cannot be called using object of the class. It can be invoked like
any normal function without using object.
5. A friend function uses the object passed to it and it uses the dot operator to
access both private and public members.
The following program uses friend function to find the area of a rectangle.
P37.CPP
//PROGRAM USING FRIEND FUNCTION
#include<iostream.h>
#include<conio.h>
class rect
{ private:
int l,b;
public:
void getdata()
{ cout<<"\nEnter length and breadth\n";
cin>>l>>b;
}
};
void main()
{ clrscr();
rect r;
r.getdata();
area(r);
getch();
}
P37.OUTPUT
Enter length and breadth
20 10
Area = 200
The following program uses friend function to find the sum of two data members of two
objects of two different classes.
P38.CPP
void main()
{ clrscr();
first a;
second b;
a.getdata();
b.getdata();
sum(b,a);
getch();
}
P38.OUTPUT
Enter a no : 10
Enter a no : 20
We have already learnt that more than one function can have the same number. But
they should differ in their number of arguments or type of arguments, which is called as
function overloading. Similar to ordinary functions, member functions can be also
overloaded. Similar to the other member functions, overloaded member functions should
be also called using object and dot operator. The following programs illustrates how
member functions are overloaded.
P39.CPP
void area(double r)
{ float ar=22.0/7*r*r;
cout<<"\nArea of Circle = "<<ar;
}
};
void main()
{
clrscr();
shape s;
s.area(10);
s.area(20,10);
s.area(10.0);
getch();
}
P39.OUTPUT
Area of square = 100
Area of Rectangle = 200
Area of Circle = 314.285706
Bit fields provide exact amount of space in terms of bits, for storing values. When we
declare a variable as char type, 1 byte of space is reserved. Similarly, for int, float and
double type variables, 2, 4 and 8 bytes of space are reserved. The entered data may not
need the entire space reserved. For example, if ‘x’ is an int type variable and the value 5
is entered for that variable. The number 5 can be represented in binary as 101, and
hence only 3 bits space is needed for that. For ‘x’, 2 bytes (16 bits) space is reserved and
13 bits spaces are wasted. Hence if the range of input data is known, the number of bits
space required can be reserved and the memory can be efficiently used. The syntax for
reserving bit space for variables is given below.
void main()
{ clrscr();
stud s;
s.getdata();
s.showdata();
getch();
}
P40.OUTPUT
Roll no = 10
Age = 19
Sex = Female
Constructors can be defined inside a class or outside a class. Similarly, when the
program is terminated and the objects are not needed, the destructor is called
automatically, which destroys these objects. The destructor also has the same name as
their class, but tilde (~) operator precedes the destructor name.
Constructors
1. Constructor should have the same name as the class in which it is defined.
2. They should be declared in the public section of a class.
3. They are invoked automatically when an object is created.
4. They do not return values and hence no return type, even void is used.
5. Constructor can be overloaded like other member functions.
6. Constructor without arguments is called as default constructor.
Destructors
1. Destructor has the same name as its class and preceded by tilde (~) symbol.
2. They do not have return type and not even void.
3. Only one destructor can be defined in a class.
4. They do not have any argument.
5. Destructor cannot be overloaded.
6. They are called automatically when the object goes out of scope.
P41.CPP
//PROGRAM USING CONSTRUCTOR
#include<iostream.h>
#include<conio.h>
class stud
{ private:
int roll;
float mark;
public:
stud()
{ roll=1;
mark=67.89;
}
void show()
{ cout<<"\nRoll No. = "<<roll;
cout<<"\n% of Mark = "<<mark;
}
};
void main()
{ clrscr();
stud s1;
s1.show();
getch();
}
P41.OUTPUT
Roll No. = 1
% of Mark = 67.889999
We have already learnt that destructors are special member functions which are invoked
automatically, when the program is terminated and the objects created are destroyed.
The tilde (~) symbol should precede the destructor name. The following program
illustrates the use of destructor. The destructor is executed one time for each object
created.
P42.CPP
//PROGRAM USING CONSTRUCTOR AND DESTRUCTOR
#include<iostream.h>
#include<conio.h>
class stud
{ int roll;
float mark;
public:
stud()
{ cout<<"\nConstructor is executing";
roll=9;
mark=89.33;
}
~stud()
{ cout<<"\nDestructor is executing";
}
};
void main()
{ clrscr();
stud a;
getch();
stud b;
getch();
}
P42.OUTPUT
Constructor is executing
Constructor is executing
Destructor is executing
Destructor is executing
Object_name.class_name :: constructor_name();
The destructor cannot be executed without using the object name. The syntax similar to
the above mentioned should be followed, which is given below.
Object_name.class_name :: ~destructor_name();
The following program illustrates how constructor and destructor can be called explicitly.
P43.CPP
P43.OUTPUT
Constructor is executing // executed when ‘a’ object is created
Constructor is executing // executed when ‘b’ object is created
x = 100
x = 100
Constructor is executing // executed due to explicit call without using object
Destructor is executing // executed due to explicit call to constructor
Constructor is executing // executed due to explicit call using object
Destructor is executing // executed due to explicit call to destructor
Destructor is executing // executed when the program is terminated
Destructor is executing // executed when the program is terminated
Every object has its own set of data members. When a member function is invoked, only
one copy of data member of calling object is available to the function. Sometimes, it is
necessary for all the objects to share data member which is common for all the objects.
If the member variable is declared as static, only one copy of the member is created for
all the objects. All objects access the same copy of static variable. The static member
variable can be used to count the number of objects created for a particular class. The
following program illustrates how static member variable is used to count the number of
objects created and destroyed.
P44.CPP
//PROGRAM USING CONSTRUCTOR AND STATIC MEMBER
#include<iostream.h>
#include<conio.h>
class stud
{ static int n;
public:
stud()
{ n++;
cout<<"\nNumber of object created : "<<n;
}
~stud()
{ n--;
cout<<"\nNumber of object exists : "<<n;
}
};
int stud::n=0;
void main()
{ clrscr();
stud s1;
getch();
stud s2;
getch();
stud s3;
getch();
}
P44.OUTPUT
Number of object created : 1
Number of object created : 2
Number of object created : 3
Number of object exists : 2
Number of object exists : 1
Number of object exists : 0
CONTENTS
● Operator Overloading
● Type Conversion
● Inheritance
▪ Types of Inheritance
▪ Single Inheritance
▪ Multiple Inheritance
▪ Multilevel Inheritance
▪ Hierarchical Inheritance
▪ Hybrid Inheritance
▪ Multipath Inheritance
● Abstract Classes
OPERATOR OVERLOADING
Operator overloading is an important and useful feature of C++. An operator is a symbol
that indicates an operation. It is used to perform operation with constants and variables.
The operators are used to form expressions. The variables used in the expressions may
be built-in data types. We can also perform operations on user defined data types. For
example, C++ allows us to add two objects, similar to adding two integers. This
mechanism of giving such special meanings to an operator is known as operator
overloading.
To define an additional task to an operator, we must specify what is should do, when the
operator is encountered. This is done with the help of a special function called operator
function, which defines the task for the operator. The general form of an operator
function is given below.
In the above form, ‘op’ is the operator which is overloaded and should be preceded by
the keyword operator.
Operator function must be either non-static member function or friend function. A friend
function will have one argument for unary operators and two arguments for binary
operators. A member function will have no arguments for unary operators and one
argument for binary operators. This is because the object used to invoke the member
function is passed implicitly and available for that member function. The operator
functions are declared in public section of the class, using the prototypes.
Unary operator uses only one operand, when it is used in expression containing built-in
data types. Similarly, the overloaded unary operator will take one only argument of user
defined data type, like object. The following program illustrates how unary operator is
overloaded using a single object.
P45.CPP
P45.OUTPUT
a=10 b=20 c=30 d=40
a=11 b=21 c=31 d=41
Binary operators can be overloaded using two operands of user defined data types.
When member function is used for overloading, the operand, say object, on the left hand
side of the overloaded operator, is passed implicitly to the operator function. The object
on the right hand side of the operator is passed explicitly to the operator function. The
following program illustrates how ‘+’ operator is overloaded to add two objects.
P46.CPP
P46.OUTPUT
X object
Enter 2 nos : 10 20
Y object
Enter 2 nos : 30 40
X: a=10 b=20
Y: a=30 b=40
Z: a=40 b=60
As we have already mentioned, like member function, friend function can also be used as
operator function, for operator overloading. An operator friend function will have one
argument for unary operators and two arguments for binary operators. The function can
be defined inside the class or outside the class. If the function is defined outside the
class, then the prototype should be mentioned inside the class. The following program
uses friend operator function to overload binary operator.
P47.CPP
void show()
{cout<<"a="<<a<<" b="<<b;
}
P47.OUTPUT
X object
Enter 2 nos : 10 20
Y object
Enter 2 nos : 30 40
X: a=10 b=20
Y: a=30 b=40
Z: a=40 b=60
● Operators can be overloaded for classes and not for built-in data types.
● An operator can be overloaded for any number times in a program, provided the
arguments are different in each overloading statement. For example. ‘+’ can be
overloaded as unary operator and binary operator in the same program.
Operator Description
. Member operator
.* Pointer to member operator
:: Scope access operator
?: Conditional operator
Sizeof() Size of operator
# Preprocessor symbols
TYPE CONVERSION
When constants and variables of various basic data types are used in an expression,
automatic type conversion takes place. But in an expression, which contains user defined
data types, the type conversion should be done by using routines. These routines, which
are normally constructors, are written by the programmer. There are three types of
conversions that are possible with user defined data types. They are:
1. Conversion from basic data type to user defined data type (say class)
2. Conversion from class type to basic data type
3. Conversion from one class type to another class type
This type of conversion is used in an expression, which contains an object on the left
hand side of the assignment operator (=) and basic data type variable or constant on the
right hand side of the ‘=’ operator. The following program illustrates the above
mentioned type conversion.
P48.CPP
P48.OUTPUT
i = 100 f = 50
i = 100 f = 12.34
In the above program, consider the following expression in the main function.
a=50;
In the above expression, ‘a’ is an object of class type and 50 is an integer constant. An
integer value cannot be assigned to an object directly. Hence the programmer writes the
constructor with an argument. When the above expression is executed, the constructor
with the argument is called and the passed integer value is stored in float data member
‘f’ of ‘a’ object. The same operation is repeated when the expression a=12.34 is
executed.
This type of conversion is used in an expression, which contains a variable of basic data
type on the left hand side of the assignment operator (=) and class type operand i.e.
object on the right hand side of the ‘=’ operator. When the compiler encounters an
expression of this type, it looks for an operator function defined for the basic type. The
programmer should write the operator function for the basic data type, for doing the
conversion. The following program illustrates the type conversion from class type to
basic data type.
P49.CPP
P49.OUTPUT
x = 100 y = 12.34
a = 100
b = 12.34
When the above program is executed, the constructor is called, which assigns the values
100 and 12.34 to the members ‘x’ and ‘y’ of the ‘z’ object, respectively. In the
expression ‘a=z’, the RHS operand is of class type (i.e. object) and the LHS operand is of
basic data type (i.e. int). When the above expression is encountered, the compiler
executes the operator function defined for ‘int’ type. The function returns the value of
integer variable ‘x’, which is assigned to ‘a’ variable. Similarly, when the expression
‘b=z’ is encountered, the compiler executes the operator function defined for ‘float’
type. The function returns the value of float variable ‘y’, which is assigned to ‘b’ variable.
This type of conversion is used in an expression, which contains objects on left hand side
and right hand side of the assignment operator (=). The programmer should write
routine to do the conversion. This routine is normally a constructor, to which the object
on the RHS of the expression is passed as argument. The constructor routine should be
defined in the target class, i.e. LHS object’s class.
P50.CPP
//TYPE CONVERSION FROM ONE CLASS TO AOTHER CLASS
#include<iostream.h>
#include<conio.h>
#include<string.h>
class xyz
{ private:
int x;
float y;
public:
xyz()
{x=1000;
y=56.5;
}
int getx()
{ return (x);
}
float gety()
{ return (y);
}
};
class abc
{ private:
int a;
float b;
public:
abc()
{ a=10;
b=12.34;
}
abc(xyz t) // constructor for type conversion
{ a=t.getx();
b=t.gety();
}
void show()
{ cout<<"\na = "<<a<<" b = "<<b;
}
};
void main()
{ clrscr();
xyz x1;
abc a1;
a1.show();
a1=x1;
a1.show();
getch();
}
P50.OUTPUT
a = 10 b = 12.34
a = 1000 b = 56.5
In the above program, the main function contains the expression a1=x1, which has two
objects of two different classes. When the above expression is executed, the constructor
of the LHS object’s class (i.e. target class abc) is called and RHS operand, i.e. ‘x1’ object
is passed to it. The type conversion constructor routine copies the values of ‘x1’ object to
‘a1’ object.
INHERITANCE
The literal meaning of the word inheritance is to receive something from the ancestors.
The meaning can be extended to the programming languages which uses the OOPS
concept. Inheritance is the most important and useful feature in C++. The mechanism of
deriving a new class from an old class is called inheritance. The old class is called as
base class and the new class is called as derived class.
The derived class inherits some or all members from the base class. Based on the
application, the objects of base class type or derived class type are created. The derived
class can also have their own members. The base class is reused to create new class and
this concept is called as Reusability. The base class is also called as Super class or
Parent class. The derived class is called as Sub class or Child class.
The base class can be inherited by private, public or private mode. The access
mode of the base class members inherited in the derived class is changed according to
the mode of derivation. The following points should be remembered during derivation.
● The private members of the base class cannot be inherited by any mode.
● The public and protected members become private members in the derived class,
after private derivation.
● The public and protected members become protected members in the derived
class, after protected derivation.
● The public derivation retains the access mode of the base class members in the
derived class also.
● The derivation mode is optional and if it is not mentioned, private mode is used
by the compiler, for derivation. In other words, the default derivation mode is
private.
The changes in the access mode of base class members are listed in the below table.
Derivation mode
Base class access mode
private protected public
private Not inherited Not inherited Not inherited
public private protected public
protected private protected protected
There are different types of inheritances based on the number of classes and
levels. They are:
1) Single Inheritance
In this type, there will be only one base class and only one derived class.
2) Multiple Inheritance
In this type, there will be more than one base class and only one derived class.
3) Multilevel Inheritance
This type is similar to single inheritance, but the derived class is used as base
class, from which another class is derived in the next level.
4) Hierarchical Inheritance
In this type, more than one class is derived from a single base class.
5) Hybrid Inheritance
In this type, more than one type of inheritance will be used. For example,
multilevel and multiple inheritances can be used to create a new derived class.
6) Multipath Inheritance
In this type, a class is derived from two or more base classes, which are derived
from same base class. Hence, there will be more than one level in this type.
Single Inheritance
When there is only one base class and only one derived class, then it is called as
Single inheritance. The members of the base class are inherited to the derived class
according to the derivation mode, as mentioned earlier. The syntax for declaring derived
class is given below.
The single inheritance can be pictorially represented as shown below, in which A is base
class and B is derived class.
A
The following program illustrates the working of single inheritance.
P51.CPP
};
class der: public abc
{ private:
int b;
public:
void showdc()
{b=20;
cout<<"\nb = "<<b;
}
};
void main()
{ clrscr();
der x;
x.showbc();
x.showdc();
getch();
}
P51.OUTPUT
a = 10
a = 20
The members of the base class and derived class after derivation are shown below.
Base class
a
Ambiguity in Single Inheritance
showbc()
If the derived class contains members whose names are same as base class members,
then ambiguity arises. When the objects are created of derived class type and if we call
the members, then derived class members override the base class members. The
following program illustrates this.
P52.CPP Derived class
a
showbc()(inherited)
// PROGRAM FOR SINGLE INHERITANCE WITH AMBIGUITY
#include<iostream.h>
#include<conio.h>
showdc()
class A
{ public:
void show()
{ cout<<"\nBASE CLASS A";
}
};
class B: public A
{ public:
void show()
{ cout<<"\nDERIVED CLASS B";
}
};
void main()
{ clrscr();
B x;
x.show(); //derived class member overrides
x.A::show(); //base class member called explicitly
getch();
}
P52.OUTPUT
DERIVED CLASS B
BASE CLASS A
Multiple Inheritance
When there are more than one base class and only one derived class, it is called
as Multiple inheritance. The members of the base classes are inherited to the derived
class according to the derivation mode, as mentioned earlier. The syntax for declaring
derived class is given below. The bases classes used for derivation should be separated
by comma.
Where dm1 is the derivation mode for base class1, i.e. bc1 and dm2 is the derivation
mode for the base class2, i.e. bc2.
The multiple inheritance can be pictorially represented as shown below, in which A and B
are base classes and C is derived class.
A B
P52.OUTPUT
x = 10
y = 20
In the above program, the members ‘x’ and ‘y’ of base classes A and B are inherited and
used by the member function show() of derived class C.
If the members of the bases classes has the same name, then ambiguity arises during
derivation. The members with same names in the bases classes are inherited to the
derived class. The scope resolution operator can be used to solve the ambiguity. The
following program illustrates this.
P53.CPP
P53.OUTPUT
CLASS B
In the above program, the derived class C contains two members inherited from class A
and B, with the same name show(). The ambiguity can be solved by defining the show()
function of class C. The show() function of class C calls the show() function of class B
explicitly.
Multilevel Inheritance
When a derived class in one level is used as a base class for deriving another class in the
next level, it is called as Multilevel inheritance. The access mode of the members derived
is changed according to the derivation mode, as mentioned earlier. The syntax for
declaring derived class is given below.
Base class
{ member declaration
};
B
P54.CPP
class B:public A
{ protected:
int y;
B()
{ y=20;
}
};
class C: public B
{ public:
void show()
{ cout<<"\nx = "<<x;
cout<<"\ny = "<<y;
}
};
void main()
{ clrscr();
C z;
z.show();
getch();
}
P54.OUTPUT
x = 10
y = 20
In the above program the members of class A (x and A() ) are inherited to class B in first
level. In the next level, the members of class B (y and B() ), including inherited members
are inherited to class C in the next level.
Hierarchical Inheritance
When more than one class is derived from a single base class, it is called as Hierarchical
inheritance. The access mode of the members derived is changed according to the
derivation mode, as mentioned earlier. The syntax for declaring base classes is given
below.
Base class
{ members declaration
};
B C
P55.OUTPUT
Enter a no : 3
Square =9
Enter a no : 4
Cube =64
Hybrid Inheritance
The hybrid inheritance can be pictorially represented as shown below, in which A and B
are base classes in level 1. Class C is the derived class, whose base class is class B, in
the next level. Class D is the final derived class, whose bases classes are classes A and
C. This hybrid inheritance contains multiple and multilevel inheritances.
A B
The following program illustrates the working of hybrid inheritance.
P56.CPP
C
//PROGRAM USING HYBRID INHERITANCE
#include<iostream.h>
#include<conio.h>
class EMP
{ protected:
Dchar ename[20];
};
class DEPT
{ protected:
char dept[20];
};
class DETAIL:public DEPT
{ protected:
long int bas,da,hra,tot;
};
class SALARY: public EMP,public DETAIL
{public:
void getdata()
{cout<<"\nEnter name,dept,basic,da and hra\n";
cin>>ename>>dept>>bas>>da>>hra;
tot=bas+da+hra;
}
void show()
{cout<<"\nName = "<<ename;
cout<<"\nDept = "<<dept;
cout<<"\nBasic = Rs."<<bas;
cout<<"\nDA = Rs."<<da;
cout<<"\nHRA = Rs."<<hra;
cout<<"\nGROSS = Rs."<<tot;
}
};
void main()
{ clrscr();
SALARY s;
s.getdata();
s.show();
getch();
}
P56.OUTPUT
Enter name,dept,basic,da and hra
Manoj Computer 10000 5000 3000
Name = Manoj
Dept = Computer
Basic = Rs.10000
DA = Rs.5000
HRA = Rs.3000
GROSS = Rs.18000
Multipath Inheritance
When a class is derived from two or more classes, which are derived from same base
class, it is called as Multipath inheritance. This type of inheritance may consists of
multiple, multilevel and hierarchical inheritances.
When a derived class has two or more base classes which have a common base class,
then duplicate copies of the grand parent will be inherited to the grand child. This can be
avoided by declaring the common grand parent as virtual base class. When a class is
declared as a virtual class, then during the derivation through different paths the
compiler will take care of avoiding the inheritance of duplicate members. This is declared
during the derivation of a base class. The access mode keyword (public, protected or
private) and keyword virtual can be any order. The following program illustrates the
use of virtual base class.
P57.CPP
P57.OUTPUT
a= 10 b= 20 c= 30 d= 40
ABSTRACT CLASSES
Abstract class is a class which is not used to create objects. It is used to inherit members
to derived classes and act as only base class. It provides a base for hierarchy of
derivation. It presents the starting of hierarchy of derivation. Based on the abstract class
several levels of inheritance can be created. Using abstract any type of inheritance can
be achieved. In the previous examples, we have used many abstract classes, on which
many classes are derived.
OBJECT ORIENTED PROGRAMMING AND C++
CONTENTS
● Pointers
▪ Pointer Declaration
▪ Pointer to class
▪ Pointer to object
▪ this pointer
● Arrays
▪ Array of classes
● Memory models
▪ Dynamic objects
Pointer Declaration
Pointer is a variable which is used to store the address of a memory location. The data in
a memory location can be accessed using the variable name as well as using its memory
address. Memory is arranged in series of bytes and these bytes are numbered from zero
onwards. It is possible to access and display the address of memory location assigned to
a variable, using ‘&’ operator. The operator ‘&’ is also called as address operator,
since it is used to get the address of a memory location. Using pointer a data can be
accessed quickly. Pointer can be used to store the address of variable of basic data types
like int, float, double and user defined data type like object. The pointer variable is
declared using the following syntax.
When pointers are used, the contents pointed by the pointers are accessed using the
operator ‘*’. The operator ‘*’ is also called as indirection operator. When pointers are
used for objects, the members of the object are accessed using ‘->’ operator. The
operator ‘->’ is also called as arrow operator, which is a combination of the symbols ‘-’
and ‘>’. However, the private members cannot be accessed even using the pointer.
P58.OUTPUT
Enter a no : 5
p->member name
(or)
(*p).member name
The pointer for an object should be declared using the following syntax.
Class_name *Pointer_variable;
The address of an object can be accessed using the ‘&’ operator with the following
syntax.
Pointer_to_object = &object_name;
P59.OUTPUT
Name = Ashok
Roll no = 12
this pointer
C++ provides a special type of pointer called this pointer, which is used to point an
object. this is a local variable of pointer to object type, which is available in all non-static
member functions in a class. When a member function of an object is called, the this
pointer of that function point to the calling object. The following program illustrates the
use of this pointer.
P60.CPP
P60.OUTPUT
Enter a number : 100
In the above program the statement n=n1.min(n2) is used to call ‘min’ member function
of n1 object. The this pointer point to the calling object n1 and returns the object n1,
which is copied to ‘n’ object. The ‘n’ object’s show function is called which displays its
‘num’ value 100, as the minimum number.
Pointers can be used to point base class as well as derived class. Pointers can be
declared as base class type or derived class type. Pointers can be used to point both
base class object and derived class object. If the pointer is declared as base class type,
then, only the members of base class can be accessed, using that pointer. Even though
the object is declared as derived class type, the pointer can point only the base class
members, if the pointer is base class type. But the derived class members can be
accessed using base class pointer, if the base class members are declared as virtual. The
concept of virtual function is discussed in later topic. If the pointer is declared as derived
class type, then it can be used to point the members of derived class object.
P61.CPP
P61.OUTPUT
b = 100
b = 100
d = 100
d = 200
In the above program, the function ‘show’ is defined in both base and derived classes.
When base class pointer is used to point base class object, the statement p->show()
calls the base class show function. When the base class pointer is used to point the
derived class object, the statement p->shows() calls only the base class show function.
When derived class pointer is used to point the derived class object, the statement
(*q).show (same as q->show) calls the derived class show function. But with the same
pointer, the base class show function can be called by using scope resolution operator
and base class name as in the statement q->B::show().
Arrays
Array is a collection of elements of similar data type. It shares a common name and each
element in an array can be accessed using the subscript or index value. Like C, the
arrays in C++ also start with the subscript 0.
Array of classes
Arrays can be used to store elements of similar basic data types like int, float, double,
char, etc. We can also use array to store user defined data type elements, like object,
which is called as array of objects. The individual object in an array of objects can be
accessed using the subscript. The following program prints whether the number is
positive or negative, using array of objects.
P62.CPP
P62.OUTPUT
Enter a no : 100
Positive
Enter a no : -50
Negative
Enter a no : 200
Positive
Enter a no : -75
Negative
Enter a no : 350
Positive
Memory Models
One of the valuable resources in a computer system is memory. There are different
types of memory models in C++, based on the size allocated for program or data. The
default memory model is small. We can set the size for memory allocated to code and
data based on the memory model.
CODE SEGMENT
DATA SEGMENT
STACK SEGMENT
EXTRA SEGMENT
During the execution of a program, the program from the hard disk is loaded into RAM.
RAM is divided into 4 segments namely,
1. Code Segment
2. Data Segment
3. Stack Segment
4. Extra Segment
Code segment is used to hold the program or code. Similarly, data segment is used to
hold data (input and output) related to the program. Stack segment is used to hold data
during the evaluation of arithmetic expressions and to store return addresses during the
execution of functions. Extra segment is used by the compiler when it is needed.
Normally the size of a segment is about 64KB. Depending on the memory model, the
program and data can use one or more segments and the size of the memory occupied
will vary, therefore. The content in code, data, stack and extra segment can be accessed
using CS, DS, SS and EX registers, respectively. The various types of memory models are
discussed in the below section.
SEGMENTS
MEMORY MODEL
CODE DATA STACK
Tiny 64 KB
Small 64 KB 64 KB
Medium 1 MB 64 KB
Compact 64 KB 1 MB
Large 1 MB 1 MB
Huge 1 MB 64 KB 64 KB
1) Tiny
The total memory capacity is 64 KB and code, data and stack should share this single
segment. This memory model can be selected if code and data are small. Programs are
executed quickly in this model.
2) Small
In this model, code can use a single segment of 64 KB. Another segment of 64 KB can be
shared by data and stack. Execution speed of the program is the same as tiny model.
3) Medium
Data and stack can share a single segment of 64 KB in this model. But code can have
multiple segments and it can avail a memory of size 1 MB. Program execution is slower
in this model. This model is suitable when the program size is large and the data size is
small.
4) Compact
In this all code should fit in a single segment of 64 KB. But data and stack can have
multiple segments and can avail a memory of size 1MB. This model is suitable for smaller
program which uses large amount of data.
5) Large
In this model, both code and data are allowed to use multiple segments and can avail a
memory of size 1 MB. Program execution is slower in this model. This model is preferred
for very big programs only.
6) Huge
In this model, code can use multiple segments and can avail memory of size 1 MB. Data
and stack can use a segment of 64 KB, each. This model is preferred for very big
programs only. Program execution is slower in this model.
C++ provides another two additional operators namely, new and delete. These two
operators are used for using the memory effectively. Even though new and delete looks
like keywords, they are operators like sizeof. The new operator not only creates an object
but also allocates memory. This operator allocates correct amount of memory needed
and hence no memory is wasted. The object created and memory allocated using new
operator should be deleted using delete operator. The delete operator not only destroys
object but also releases the memory allocated.
The functions malloc() and free(), used in C are for individual data. But new and delete
operators are suitable for objects. Another difference between new operator and malloc
function is that, new operator can be overloaded, whereas malloc cannot be. The
following program uses new operator for allocating memory to store elements of basic
data type, say of integer type.
P63.CPP
P63.OUTPUT
Value = 1 Address = 3520
Value = 2 Address = 3522
Value = 3 Address = 3524
Dynamic objects
Normally objects are created during compilation time. But we can also create objects
during the execution time or run time. Such objects are called as dynamic objects.
Dynamic object can be created using new operator and can be pointed by pointer to that
object. Since pointer is used to access the object, object name need not be specified in
the program. The following program illustrates how dynamic objects can be created.
P64.CPP
P64.OUTPUT
x = 100
In the above program, an object is created dynamically, of the type num. The object is
pointed by the pointer ‘p’. Using the pointer the member function show is accessed
which displays 100 as output.
We can use the name of a member function of base class to a member function of
derived class also. During the compilation time, the compiler will link the appropriate
member function to the call to the member function. This is called as early binding or
static binding.
Consider a situation in which the base class and the derived class are having member
functions with the same name. We use a pointer of base class type to point a derived
class object. If we call the member function of an object of derived class type, the
member function of base class will be executed. We can override the member function of
base class and we can execute the member function of derived class. This can be done
by declaring the base class member function as virtual.
When a base class function is declared as virtual, it will be overridden when we use base
class pointer to point derived class object. The selection or linking of derived class
function is done during the run time. This is called as late binding or dynamic
binding. This process of selecting member function is called as run time
polymorphism.
P65.CPP
P65.OUTPUT
BASE
DERIVED
In the above program, the first p->show statement will execute the show function of
base class, since the pointer ‘p’ points to the base class object. Similarly, when the
second p->show statement is executed, the member function of base class will be
executed normally, since the pointer is base class type. But, since the base class
function is declared as virtual, it was overridden and the show function of derived class is
executed.
CONTENTS
● Files
▪ File modes
● Templates
● Exception handling
FILES
File is a collection of data stored on the disk. The data is saved in a file and stored in
disk, which can be retrieved for later use. The stored data can be retrieved for
reading or updating. The console I/O functions like cin, cout, etc. reads data through
input devices and displays on the screen. The data read through these functions are
temporarily stored in variables or in arrays. When the program is terminated, the
data are vanished. These data can be stored permanently in disk using disk I/O
functions.
Stream is flow of data. In OOPS, the streams are controlled using the classes. The two
important operations performed on files are read and write. C++ provides various
classes to perform these operations. The ios class is the base class. All other classes
are derived from the ios class. These classes contain several member functions that
perform input and output operations.
The istream and ostream classes control input and output functions respectively. The
ios class is the base class of these two classes. The member functions of theses
classes handle formatted and unformatted operations. The functions get(), getline()
and read() are defined in the istream class. The functions put(), and write() are
defined in the ostream class.
The iostream class is also a derived class. It is derived from istream and ostream
classes. The classes ifstream and ofstream are derived from istream and ostream
respectively. These classes handle input and output with the disk files. The header
file fstream.h contains declarations of ifstream, ofstream and fstream classes
including iostream.h file. This file should be included in the program while doing disk
I/O operations.
ios
File modes
istream ostream
Whenever we want to perform any operation on file, it should be opened. There are
various modes for opening a file. A file can be opened using open() function with two
ifstream ofstream
arguments. The syntax of open() function is given below.
ifstream in;
in.open("text",ios::in);
cout<<"\nContents of file"<<endl;
while(in.eof()==0)
{ in>>data;
cout<<data;
}
getch();
}
P66.OUTPUT
Enter text : cplus
Enter another text : plus
Contents of file
cplusplus
In the above program, first a file named ‘text’ is opened for writing the data. The data
entered through the keyboard are stored in the file. The file is closed and opened in
append mode. Now the entered data are stored at the end of the opened file. The file is
closed and opened in read mode. The contents of the file are retrieved and displayed on
the screen. The eof() function returns 0, till it reaches the end of the file.
The contents in a file can be accessed randomly (i.e. from any location) or sequentially.
When the file is accessed sequentially, the contents are read or written character wise.
The characters are read one by one during reading operation. Similarly, during writing
the characters are written into the file one by one. The functions put() and get() are used
for reading/writing character one by one. The read() and write() functions read and write
a block of data. The following program illustrates the sequential read and write
operations on a file.
P67.CPP
//FILE PROGRAM USING SEQEUENTIAL FILE READ/WRITE
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
void main()
{ clrscr();
int l=0;
char text[20];
cout<<"\nEnter text : ";
cin.getline(text,20);
fstream io;
io.open("data",ios::in|ios::out);
while(text[l]!='\0')
io.put(text[l++]);
io.seekg(0);
char c;
cout<<"\nEntered text: ";
while(io)
{ io.get(c);
cout<<c;
}
io.close();
getch();
}
P67.OUTPUT
Enter text : programming in c++
In the above program, the input entered by the user through the keyboard is stored in a
character array called ‘text’. Next, a file named ‘data’ is opened in read/write mode. The
put() function stores the characters one by one, from ‘text’ array to the file ‘data’. The
seekg(0) function moves the file pointer to the beginning of the file. Next, the get()
function reads the character one by one, from the file ‘data’ file and displays it on the
screen. And finally, the file is closed.
There are two types of files namely, ASCII and binary file. When ASCII files are used, the
file I/O functions read/write the data in ASCII form. Similarly, when binary files are used,
the contents of the file are processed in binary format. The ASCII file occupies more
space than binary file, for numeric data. The binary file format is suitable for numeric
data. When ASCII files are used, even the numeric data are represented as ASCII value,
which occupies more memory. For example, if we store the integer 5 in ASCII file, only its
ASCII value 53 is stored. Here the characters 5 and 3 occupies one byte memory each,
and hence occupies 2 bytes space totally. But if 5 is stored in binary file, only its binary
value 101 is stored, which requires only 1 byte of memory. Hence binary is suitable for
numeric data.
When we use binary file, the functions read and write are used to retrieve and store
data. The following program illustrates the operations of read and write functions for
binary file.
P68.CPP
P68.OUTPUT
100 200 300 400 500
In the above program, a binary file named ‘data’ is opened for writing. The contents in
the array ‘num’ are stored into the file, using write function and the file is closed. Then
the contents of the array are cleared. Next, the file is opened for reading. The contents
of the binary file is read and stored in the ‘num’ array. And finally, the contents of the
array are displayed on the screen.
Updating is routine task in the maintenance of any data file. The updating would include
one or more of the following tasks:
These actions require the file pointer to move a particular location in the file where the
required item is present. This is called as Random access operation in file. This can be
easily implemented if the file contains a collection of items/objects of equal lengths. In
such cases, the size of each object can be easily obtained using sizeof operator.
The tellg() function gives the total number of bytes in a file i.e the file size. The total
number of objects or items can be obtained by dividing the file size by total number of
objects/items. The starting location of mth object/item can be obtained as follows:
We can move the pointer to this location to access the mth object/item. The following
program performs the operations, in the file STOCK.DAT, which are listed below.
P69.OUTPUT
CURRENT CONTENTS OF FILE
AA 11 100
BB 22 200
CC 33 300
ADD AN ITEM
Enter name : DD
Enter code : 44
Number of objects = 4
Number of bytes = 56
Enter object no. to be updated : 4
Enter name : ZZ
Enter code : 99
The file STOCK.DAT initially contains 3 objects. The first while loop displays these
objects. Next, the EOF flag is cleared and a new item was appended at the end of the
file. The second while loop displays the updated content of the file. The object number
which is to be modified was entered by the user and the file pointer is moved the
location of that object. The new values for that object was entered and stored in the file.
The last while loop displays the modified content of the file.
TEMPLATES
Template is one of the most useful features of C++. In templates, generic data types are
used as arguments and they can handle a variety of data types. A function that works for
all C++ data types is called as generic function or template function. The formal
parameters of template function are declared as generic data type. Hence we can pass
any type of data to that function. Normally we will use many functions with same
number, for different type of arguments. This is called as function overloading, which
increases the size of the program. If the functions perform same operation for different
types of data, we can use one template function which reduces the program size.
Similarly, a template class can handle any type of data members. The templates should
be declared using the following syntax.
P70.CPP
P70.OUTPUT
c=A
c = 100
c = 3.14
In the above program, T is declared as the generic data type, in the template
declaration. The formal parameter ‘c’ of the constructor is declared of type T and hence
can accept any type of data passed to it. When the object is created, the data type of the
actual parameter should be mentioned before the object name and they should be
enclosed between the angled brackets ‘<’ and ‘>’. When the objects are created the
parameters are passed to the constructor and they are displayed.
P71.OUTPUT
x=A
x = 100
x = 12.34
In the above program, the function show is declared as a template and its formal
parameter is declared as generic data type. Hence the function can accept any type of
data passed to it. The function show is called with different types of data which are
received by the function and displayed.
P72.OUTPUT
x=B
y=Z
x = 200
y = 500
x = 3.14
y = 56.78
In the above program, the data member ‘x’ of the class ‘data’ is declared as generic data
type. The function show is a template function. The formal parameter of the constructor
function is also declared as generic data type. When the objects are created, the
different types of parameters are passed to the constructor. These parameters are
copied to the template data member ‘x’. Similarly, the formal parameter of show
function is also of generic data type and it can receive and display any type of data
passed to it. Also note that ‘x’ is the generic data member of the objects and ‘y’ is the
formal generic argument.
The following program illustrates the use of multiple template data members.
P73.CPP
P73.OUTPUT
x=B
y = 100
x = 200
y = 12.34
In the above program, ‘x’ and ‘y’ are data members of the class ‘data’. The formal
arguments of the constructors are declared as generic data type. When the objects are
called with multiple parameters, they are received by the constructor and are assigned
to the template data members ‘x’ and ‘y’.
EXCEPTION HANDLING
It is a mechanism used to handle the run time errors during the execution of a program.
Some errors like syntax errors are identified by the compiler during the compilation time.
But some errors like division by zero, incorrect input data type, domain error, etc. cannot
be identified during compilation time. These errors are called as run time errors and they
can be handled using exception handling mechanism.
The error occurred during the execution of a program is called as exception. The
segment of a program where an error can occur is mentioned in a block called try block.
When an error has occurred, the object caused that error is thrown using a block called
throw block. The catch block in the program will catch the object and execute the
statements enclosed in that block. A program can have multiple catch blocks for a single
throw block. The catch block whose argument is matched with the thrown object is
executed.
P74.CPP
P74.OUTPUT
Enter 2 numbers : 8 5
Subtraction = 3
Enter 2 numbers : 5 8
Exception - 1
P75.CPP
void main()
{ clrscr();
num(0);
num(1);
getch();
}
P75.OUTPUT
Zero
Character