OOPs With C++ Programming
OOPs With C++ Programming
Programming
Kiran Gurbani
B.E., MCA, [Link].,
Head of Computer Science and IT Department,
R.K. Talreja College,
Ulhasnagar - 3, Dist.
Thane, Maharashtra.
Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,
“Ramdoot ”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.
Phone: 022-23860170, 23863863; Fax: 022-23877178
E-mail: himpub@[Link]; Website: [Link]
Branch Offices :
New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj, New Delhi - 110 002.
Phone: 011-23270392, 23278631; Fax: 011-23256286
Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.
Phone: 0712-2738731, 3296733; Telefax: 0712-2721216
Bengaluru : Plot No. 91-33, 2nd Main Road, Seshadripuram, Behind Nataraja Theatre,
Bengaluru - 560 020. Phone: 080-41138821; Mobile: 09379847017, 09379847005
Chennai : New No. 48/2, Old No. 28/2, Ground Floor, Sarangapani Street, T. Nagar,
Chennai - 600 017. Mobile: 09380460419
Pune : “Laksha ” Apartment, First Floor, No. 527, Mehunpura, Shaniwarpeth (Near Prabhat Theatre),
Pune - 411 030. Phone: 020-24496323, 24496333; Mobile: 09370579333
Lucknow : House No. 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,
Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549
Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang Pura,
Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847
Ernakulam : 39/176 (New No. 60/251), 1st Floor, Karikkamuri Road, Ernakulam, Kochi - 682 011.
Phone: 0484-2378012, 2378016; Mobile: 09387122121
Cuttack : New LIC Colony, Behind Kamala Mandap, Badambadi,
Cuttack - 753 012, Odisha. Mob.: 9338746007
Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank, Kolkata - 700 010.
Phone: 033-32449649; Mobile: 07439040301
- Kiran Gurbani
Preface
It gives me immense pleasure to present this First Edition of “OOPs with C++ Programming”
to the teachers and students of Bachelor of Computer Science and Information Technology. This book
has been written as per the syllabus prescribed by the Indian Universities.
The first C with Classes compiler was called Cfront, which was derived from a C compiler called
CPre. It was a program designed to translate C with Classes code to ordinary. In 1983, the name of the
language was changed from C with Classes to C++. The ++ operator in the C language is an operator
for incrementing a variable, which gives some insight into how Structure regarded the language. (At
my institution, C++ is the first language introduced, immediately followed by C.)
The chapters in this book mainly focuses on new features added around this time, the most
notable of which are OOPs concepts, constructor, destructor, virtual functions, function and operator
overloading, file handling, templates, references with the & symbol, the const keyword, and single-
line comments using two forward [Link] concept and theory of each topic is followed by the
theoretical explanation and some self-assessment questions. All practical solutions of C++ are
provided.
I have tried my level best to give everything in this book in proper manner. Still few points from
book may be explained in better way than presently are there in the book.
Constructive suggestions and comments from the users will be sincerely appreciated. I would
appreciate hearing from you about any textual errors or omissions which you identify. If you would
like to suggest improvements or to contribute in any way, I would be glad to hear from you.
Please send correspondence to kiranrktcollege@[Link]
Last but not the least, I would like to give big lifetime thanks to Mr. S.K. Srivastava, Himalaya
Publishing House Pvt. Ltd. for providing an environment which stimulates new thinking and
innovations and his support, motivation, guidance, cooperation and encouragement to write this book.
I am very grateful for his support and thank him for his true blessings.
Kiran Gurbani
kiranrktcollege@[Link]
Mob.: 7769979964
Contents
1. Introduction to OOPs and C++ with Variable and Operators 1 – 28
3. Functions in C++ 42 – 55
Chapter Outline
1.1 Introduction to C Language
1.2 Compilers and Interpreters
1.3 Difference between C and C++
1.4 Software Evolution (Evolution of Programming Language)
1.5 Object Oriented Programming Paradigm
1.6 Benefits of OOPs/Features of OOPs and C++
1.7 Applications of OOPs
1.8 What is C++?
1.9 Features of C++ Language
1.10 Structure of C++ Program
1.11 Basic Data Types in C++
1.12 C++ Operators
1.13 Preprocessor Directive
1.14 Declaration of Variables
1.15 Input and Output
Origin of C:
Dennis M. Ritchie, a systems engineer at Bell Laboratories, New Jersey developed C in the early
1970’s.
BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is
also used to develop any kind of application, including complex business ones. The following is a
partial list of areas where C language is used:
Embedded Systems
Systems Programming
Artificial Intelligence
Industrial Automation
Computer Graphics
Space Research
Image Processing
Game Programming
C language can be used for creating system programs, but it does not support Object concepts &
data hiding concept. Every variable and functions are public in scope, hence no data hiding concept
can be provided. C does not support object oriented concepts like Data encapsulation, Data
Polymorphism, Data Abstraction, Data Inheritance. To Provide these We will switch to C++ language
with powerful data hiding concepts.
In C language templates can not be created. In C++ language templates can be created.
C language does not support exception handling. C++ language supports exception handling.
C language does not support the concept of virtual C++ supports the concept of virtual function with
functions. the help of abstraction and Inheritance.
1, 0
Machine Language
Assembly Language
Procedure-oriented Language
Structured Programming Language
Object Oriented Programming
Software technology has a growth of a tree. Software evolution has a layer of growth. Each layer
representing an improvement over the previous one.
Initially the programs are to be written in machine language but it is in the form of 0’s and First
hence difficult to remember.
Second layer of assembly language which has Mnemonics in the form of English language.
Language used by ALU section of the CPU.
Third layer is procedure oriented language (POP) language. In this problem is viewed as a
sequence of Instructions. All functions or tasks are combined in one procedure program.
In the fourth layer the program is divided into functions. Instructions of the program is divided
into groups known as functions.
In multi function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. In the fifth layer,
modularization is used with the help of functions and in large programs it is very difficult to identify
what data is used by which function. Hence data hiding concept can be provided using functions.
In object oriented following characteristics are followed:
1. Large programs are divided into smaller programs known as functions called objects.
2. Data hiding concept is provided.
Introduction to OOPs and C++ with Variable and Operators 5
Data Data
Communication
functions functions
Object C
functions
Data
1. Objects:
(a) Objects are the basic Run-time entities also called as Real World thing.
(b) An object in C++ is a representation of some physical, logical or conceptual entity. For
example, an object can be a vehicle, bank account, animal, place, a table of data, any item,
or it represents a person etc.
(c) Every object is identified by its own properties and methods which indicates behaviour,
states and tasks of object.
(d) The object can take place in memory and associated in a memory like a structure in C or
Record in pascal.
(e) An object is an instance of user-defined data type called class. We can also say that object
is a variable whose type is a user defined class.
(f) When a program is executed, the objects interact by sending messages to one another.
For example 1, if customer and account are two objects, customer object may send a message to
the account object requesting for the bank balance.
For example 2, if student and marks are two objects, student object may send a message to the
marks object requesting for grade of student.
Customer Object Account Object
Object : student
Data: Name
Date of Birth
Marks
Functions: Total
Average
Display
2. Classes:
(a) Class is predefined blank template or blueprint which can be reused number of times.
(b) The entire set of data and code of an object are wrapped together in one capsule also
called user-defined data type called class.
(c) Class encapsulates the Attributes and behaviour of an entity.
(d) Class specifies what data and what functions will be included in objects of that class.
(e) Classes are user-defined data types and behave like the build-in types of a programming
language.
Introduction to OOPs and C++ with Variable and Operators 7
(f) Once a class has been defined, we can create any number of objects belonging to that
class. Thus class is collection of objects of similar type.
(g) Class construct supports data hiding concept by combining data and code in one unit with
powerful keywords private, protected and public.
(h) The syntax of declaring class is
Class classname
{ scope:
data members;
scope:
member functions;
}
Class student
{ private:
int rollno;
Char name [10];
public:
void getdata();
void display();
}
3. Data Abstraction:
(a) Abstraction refers data hiding, this indicates that only essential things will be known to
the user and non essential things will be abstracted or hided from the user.
(b) Abstraction refers to the way of representing essential features without including
background details and explanations. This states that only foreground details will be
shown to the user and background details will be hided.
(c) Abstraction permits the programmer to look at something without being concerned with
its internal details.
(d) Abstraction in structure program shows the task performed by the function, but it hides
from the client actually how function executes internally and how task is performed. This
is called functional abstraction.
(e) This insulation of the data from direct access by the program is called data hiding or
information hiding.
(f) Classes uses the concept of data abstraction are known as Abstract Data Types (ADT).
(g) Simple pen object may have different properties or attributes like its essential features are
colour, cost, ballpen or inkpen but non essential features are like type of ink, raw material
used for plastic of pen.
(h) Encapsulating together data/information hiding feature allows limited visibility to the
class users. Access specifiers like private, protected, public in C++ are used to implement
data hiding.
(i) Abstraction helps in managing the complexity of the software.
8 OOPs with C++ Programming
4. Data Encapsulation:
(a) The internal data of a class i.e. data members and member functions are first separated
from outside world and then they are put in a unit is called encapsulated unit.
(b) Encapsulation groups all pieces of object into one packet.
(c) Encapsulated data is not accessible outside the world. It can be accessed only by member
functions which are declared within a class.
(d) This insulation of the data from direct access by the program is called data hiding or
information hiding.
(e) All the essential properties of the objects are encapsulated in a class. The attributes are
called as data members to hold information. The functions that operate on these data are
called methods or member functions.
5. Inheritance:
(a) Inheritance is the process of creating new classes, called derived classes, from existing
classes. These existing classes are often called base classes.
(b) The derived class inherits all the properties and methods of the base class and can add
new features, properties and methods of its own, based on requirement. By adding these
refinements the base class remain unchanged.
(c) Inheritance is the process by which objects of one class acquire the properties of objects
of another class.
(d) C++ allows a programmer to create hierarchical classification i.e. it supports parent-child
relationship.
(e) The parent class is a base class also called super class and the child class is also called as
derived class or sub class.
(f) The concept of inheritance provides the idea of reusability. This means we can reuse
existing classes many times and also can add additional features to an existing class with
modifying it. Reusability concept saves lot of money and time. Reusability code helps in
case of distributing class libraries. Reusability increases program reliability.
(g) Inheritance is similar to inheriting characteristics from our parents.
Bird
Attributes
Features
Lay eggs
6. Polymorphism:
(a) Poly means many, morphism means many forms, i.e. more than one form of operation.
(b) Polymorphism indicates the ability to take more than one form.
(c) More than one form of operation may behave differently by creating different instance.
(d) The behaviour change of object depends upon the types of data used i.e. one thing
behaves differently at different places.
(e) Polymorphism allows objects having different internal structures to share the same
external interface.
(f) It supports function overloading and operator overloading concept. Function overloading
indicates that functions of a class with same name but either different number of
arguments or different types of arguments.
You can not overload a function which can have same number of arguments of same type
and in same sequence and differing only in their return types.
For example,
You behave differently when your friend asks about something and when your boss asks
something.
Example,
Same name sum function can be used for addition of two integers, addition of two floats,
addition of three integers.
sum (int a, int b);
sum (float x, float y);
sum (int a, int b, int c);
It is also called as function polymorphism.
When a single function name is used to perform different types of tasks is called function
overloading. This is same as like a particular word having several different meanings
depending on the context.
(g) In operator overloading we can overload the in-built operators as well as user-defined
data types. You can not change the semantics of an operator.
Existing operator like ‘+’ can be used for addition of two integers and also can be used
for addition of two float or ‘+’ sign can be used for concentration of two strings.
Overloading can not alter the basic template of operator.
Shape
Draw()
7. Dynamic binding:
(a) Dynamic binding is a binding at Run time.
(b) Dynamic binding is also called as late binding.
(c) Binding refers to the linking of procedure call or function call to the code or definition to
be executed in response to the call.
(d) The code associated with a given procedure call or function call is not known until the
time of the call at run-time.
(e) With the help of dynamic binding, one can access method of a derived class using a
pointer of a base class depending on to which object it points to at run-time.
8. Message passing:
(a) Object oriented consists of a set of objects that communicate with each other.
(b) Message passing involves following steps:
(i) Creating classes that define objects and their behaviour.
(ii) Creating objects from class definitions.
(iii) Establishing communication among objects.
(c) Objects communicate with one another by sending and receiving information or by
passing messages.
(d) A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired result.
(e) Message passing involves specifying the name of the object, the name of the function i.e.
message and the information to be sent.
(f) Customer is an object.
Balance is a message
Account no. is an information
Customer. Balance (account no)
Object Message information
(g) The communication between objects is feasible as long as it is alive.
Example:
# include <iostream.h>
int main ()
{
cout <<”Welcome to C++”;
return 0;
}
structure array
union function
class pointer
enumeration reference
(iii) It uses enum keyword which automatically enumerates a list of words by assigning them
values 0, 1, 2 etc.
(iv) By default, enumerators are assigned integer value starting with 0.
C. Derived data types:
(a) Arrays: Array is a derived type. It is a collection of similar data elements. It can be
collection of integers, collection of characters.
datatype arrayname [size of array]
int x[10];
data objects are stored in consecutive memory locations under a common heading or variable
name.
(b) functions: functions are the derived functions are called user defined function to perform
specific task. Compare to C there is lots of modification in C++ due to object oriented in
concept.
(c) Pointer: Pointers can be used to point and reference address of another variable. In C++
concept of constant pointer and pointer to a constant pointer can be used.
e.g. char const * P1 = “Welcome”;
pointer allows to return structured variables from function.
It allows to pass variables, arrays, functions, strings and structures as function argument.
It supports dynamic allocation and deallocated of memory segments.
Size of range of C++ Basic data type
Sr. No. Type Bytes Range
1. Char 1 – 128 to 127
2. Unsigned char 1 0 to 255
3. Signed char 1 – 128 to 127
4. Int 2 – 32768 to 32767
5. Unsigned int 2 0 to 65535
6. Signed int 2 – 32768 to 32767
7. Short int 2 – 32768 to 32767
8. Unsigned short int 2 0 to 65535
9. Signed short int 2 – 32768 to 32767
10. Long int 4 – 2147483648 to 2147483647
11. Signed long int 4 – 2147483648 to 2147483647
12. Unsigned long int 4 0 to 4294967295
13. float 4 3.4 E – 38 to 3.4 E +38
14. Double 8 1.7E – 308 to 1.7 E + 308
15. long double 10 3.4 E – 4932 to 1.1 E + 4932
16 OOPs with C++ Programming
(2)
Assignment
Operators
(3)
Comparison and
Relational Operators
Logical operators
Logical Operators
Equality Operators
(4)
Bitwise Logical Operators
(5)
Special Operators (a) Unary operators
(b) Ternary operator
(c) Comma operator
(d) Scope operator
(e) New and delete operator
(f) Other operators
1. Arithmetic Operators
The operators used to perform arithmetic operations such as addition (+), subtraction (–),
multiplication (*), division (/) are called arithmetic operators. These basic operators are known as
binary operators as they require two variables to be evalued.
Sr. No. Operator Meaning
1. + Addition or unary plus
2. – Subtraction or unary minus
3. * Multiplication
4. / Division
5. % Modulo division (Reminder of an Integer division)
The variables or constants on which operators are operated are known as operands. The
arithmetic in C++ can be of three types:
(a) Integer Arithmetic.
(b) Real Arithmetic.
(c) Mixed Mode Arithmetic.
(a) Integer Arithmetic: When both the operands are integers, the operation is called integer
arithmetic.
For e.g.,
55 – 5 = 50
55 + 5 = 60
14 * 2 = 28
14/2 = 7 (Decimal part truncated integer division)
14% 2 = 0 (Remainder of division)
– 14 % 3 = – 2
14 % 3 = 2
6/7=0
Introduction to OOPs and C++ with Variable and Operators 17
(b) Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic. A real operand may assume values either in fractional or exponential form.
For e.g.,
1.5 – 0.7 = 0.8
1.5 + 0.7 = 2.2
1.5 * 2.0 = 3.0
6.0/7.0 = 0.857143
1.0/3.0 = 0.3333
– 2.0/3.0 = – 0.666667
% (modulo operator) can not be used with Real numbers
x_int/y_int = result_int
x_int/y_float = result_float
x_float/y_int = result_float
x_float/y_float = result_float
(c) Mixed Mode Arithmetic: C++ permits us to mix integer operand with real operand. When
one operand is real and the other is integer, the expression is called mixed mode arithmetic
expression i.e. if either of the operand is of the real type, then only real operation is
performed and result is always a real number.
For e.g.,
15/10.0 = 1.5
4 + 3.5 = 7.5
2. Assignment Operators
Assignment operators are used to assign the result of an expression or constant to variable.
The assignment operators can be used within any valid expression, the usual assignment operator
is ‘=’.
variable_Name = constant or expression;
The arithmetic expression is a combination of variables, constants and operators
E.g., x = a + b;
z = 0;
final = 100;
During the assignment operator the value of expression of right hand side is assigned to left side
variable.
During the assignment operator the value of the expression on right hand side is computed and is
assigned to the variable on the left hand side.
Short hand assignment operators:
In addition to the usual assignment operator ‘=’. C++ has short hand assignment operators of the
form.
variable op = expression;
18 OOPs with C++ Programming
Example:
! (a < b) || (c > b)
! (4 < 5) || (6 > 5)
! (true) || (true)
false || true
true
(c) Equality Operators: These operators are used to check the equality of the given expression
or statement.
== is a comparison operator between two expressions used for equality check.
!= is a comparison operator between two expression used for not equality check.
Expression Result
a == b false if a = 4, b = 6
(a * b)! = c true if a = 4, b = 6, c= 8
‘s’ == ‘k’ false
Operator Meaning
== Equal to
!= Not equal to
4. Bitwise Logical Operators
C++ is having powerful features is the set of bit manipulation operators. These permits the
programmer to access and to manipulate individual bits within piece of data.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR (EXOR)
>> Bitwise right shift
<< Bitwise left shift
~ Bitwise complement
(a) Bitwise AND: The bitwise AND operation will be carried out between the two bit patterns
of the two operands.
Variable Value Binary pattern
x 5 0101
y 2 0010
x&y 0 0000
a 6 0110
b 3 0011
a&b 2 0010
To generate a 1 bit in the result, bitwise AND need a one in both numbers.
Introduction to OOPs and C++ with Variable and Operators 21
(b) Bitwise OR: The bitwise OR operations result 1 if any one of bit value is 1.
Bitwise OR
Variable Value Binary pattern
x 5 0101
y 2 0010
x/y 7 0111
a 6 0110
b 1 0001
a/b 7 0111
(c) Bitwise Exclusive OR: The bitwise exclusive OR will be carried out by the notation ^. To
generate a 1 bit in the result, a bitwise exclusive OR needs a one in either number but not
both.
Bitwise EX – OR
Variable Value Binary pattern
x 5 0101
y 2 0011
x^y 7 0111
a 6 0110
b 3 0011
a^b 5 0101
(d) Bitwise Right shift: The right shift >> operator is used for right shifting. For y = 41 binary
pattern is 0010 1001.
y >> 3 will result
0010 1001
00010100 *****shift
00001010 *****shift
00000101 *****shift
y >> is 0000 0101
(e) Bitwise Left shift: The << operator is used for left shifting. For y = 41 binary pattern is
0010 1001.
Variable Value Binary pattern
x 33 0010 0001
x << 3
0010 0001
shift *** 01000010
shift *** 10000100
shift *** 00001000
x << 3 is 00001000
22 OOPs with C++ Programming
(f) Bitwise complement: The complement operator ~ switches all the bits in a binary pattern
that is all the zeroes become ones and all ones become zeroes. It acts as a 1’s complement.
Variable Value Binary pattern
x 23 0001 0111
~x 132 1110 1000
y ff 1111 1111
~y 00 0000 0000
5. Special Operators
There are some special operators used in C++ language to perform particular type of operations.
(a) Unary operators.
(b) Ternary operators.
(c) Comma operators.
(d) Scope operators.
(e) New and delete operators.
(f)Other operators.
(i) parentheses for grouping expression.
(ii) Membership operators (Manipulators).
(a) Unary operators: The unary operators require only a single expression to produce a line.
Some unary operators may be followed by the operands such as incrementer and
decrementer.
The most common unary operation is unary minus, where a minus sign precedes a numerical
constant, a variable or an expression.
Operator Meaning
* Contents of the storage field to which a pointer is pointing. Hence * is used to get the
content of the address operator. Pointing to a particular memory.
& Address of variable
– Negative value (minus sign)
~ Bitwise complement
++ Incrementer
i++ post increment
++i pre increment
i++ i = i + 1 i = 5 + 1 6
–– Decrementer
i – – post decrement
– – i pre decrement
i––i=i–1i=5–14
type forced type of conversion
sizeof size of the subsequent data type or type in byte. It is used to direct the compiler to reserve
the memory size or block to the particular data type.
Introduction to OOPs and C++ with Variable and Operators 23
(b) Ternary operator (?:): C++ includes a very special operator called the ternary or
conditional operator. It is called ternary operator because it uses three expressions. It is short
hand version of if_else construct.
The format of the ternary operator is expression1?expression2:expression3
If expression1 evaluated is true then expression2 is evaluated otherwise expression3 is
evaluated.
Example,
(1) if (i % 2 = = 0)
even = true
else
even = false
even = (i % 2 = = 0)? true : false;
(2) if (i > j)
max = i
else
man = j
max = (i > j)? i : j;
(3) if (x > y)
x=x+3
else
x=x–3
x = (x > y)? x + 3 : x – 3;
(c) Comma operator: C++ uses a comma operator in two ways:
1. The first use of comma is as a separator in the variable declaration int a, b, c;
float x, y, z;
2. The second use of comma is as a separator used in for loop.
for (i = 1, j = 2; i < = 10; i++, j +=3)
{
cout <<i<< ‘‘ “ <<j<<endl;
}
(d) Scope operator (::): The double colon (::) sign is used as the scope resolution operator in
C++.
The scoping operator is used in a class member function definition.
(e) New and delete operators: C++ has two unary operators new and delete are used. The
dynamic memory allocation and deallocations are handled through library functions such as
malloc, alloc, calloc and free routines.
The new operator performs the task of allocating memory dynamically at Run-time.
The delete operator is used to deallocate memory or free memory, i.e. memory management
can be provided with new and delete operator.
24 OOPs with C++ Programming
Variable is a place holder which occupies memory space to store variable value, or a
constant value, integer, float, character, string value.
The variable name follows following rules:
(a) The variable name should always start from any alphabet a – z.
(b) The variable name is combination of alphabets, numbers and underscores.
(c) The variable name can not start with digit.
(d) No special symbol other than underscore can be used in variable name.
Syntax of declaration of variable:
data_type variable name;
e.g., int x; double ratio;
int x,y; char c;
float avg; char x[10];
2. Dynamic Initialisation of Variables: C++ allows us to initialize the variable at Run time.
Initialisation of variables at run time is referred as dynamic initialisation.
int m = 10;
float area = 3.1415 *r *r;
Here both declaration and the initialisation of variable can be done simultaneously.
float avg = sum/3;
Initialises avg at Run time i.e. dynamic Initialization of avg.
3. Reference Variables:
(a) Reference variable provides an alias for a previously defined variable.
(b) It is called alternative name of original variable.
(c) Example: If we make the variable sum a reference to the variable total, then sum and
total can be used interchangebly to represent that variable.
(d) data type reference name = variable name
int sum = 100;
int & total = sum;
Here total is the alternative name declared to represent the variable sum.
(e) A reference variable must be initialized at the time of declaration.
(f) C++ assigns additional meaning to the symbol ‘&’. Here & is not an address operation. The
notation int & means reference to int.
Example,
void fun(int&x) // uses reference
{
x = x + 10;
}
int main ()
{
int n = 10;
Introduction to OOPs and C++ with Variable and Operators 27
fun (n);
return 0;
}
When the function call fun(n) is executed then value of actual parameter n is passed to formal or
reference parameter x i.e. if x is incremented n is also incremented. n refers the x value. Hence it is
called as call by reference.
2. Input operator
The Cin statement is used as a input operator. In this Cin object is used to read number of
characters or stream of characters from standard input device. This input statement causes the program
to wait for the user to type in a number. The Cin is predefined object in C++ that corresponds to the
standard input stream.
This stream represents the keyboard. The operator >> is a extraction or get from operator. It
extracts or takes the value from the keyboard and assigns it to the variable on its right.
It is similar to scanf() function in C.
Extraction
operator Variable
Object
C in 45.5
Keyboard
int a;
cin>>a;
int a, b;
cin>>a>>b;
Control Structures
2 and Loops
Chapter
Chapter Outline
2.1 Introduction to Control Structures
2.2 Types of Control Structures
2.3 Selection Statements
2.4 Repetition (Loops)
2.5 GOTO Statement
2.6 Break Statement
2.7 Continue Statement
The stmtT can be a simple or compound statement. Simple involves 1 single statement.
Compound involves 1 or more statements enclosed with curly braces { }. A compound statement is
called a block statement.
Example 1: Simple statement
int c = 3;
.
.
if ( c > 0 )
cout << "c = " << c << endl;
Example 2: Compound statement
int c = 10;
.
.
if ( c > 5 )
{
b = 2 * b + c;
cout << c * c * b << endl;
}
Two-Way Decisions: Two-way decisions are handled with “if / else statements” and either do
one particular thing or do another. Similar to one-way decisions, the decision is based on a logical
expression. If the expression is true, stmtT will be executed; if the expression is false, stmtF will be
executed. The form of a two-way decision is as follows:
if ( logical expresion )
stmtT;
else
stmtF;
stmtT and stmtF can be simple or compound statements. Remember that compound statments are
always enclosed with curly braces { }.
Multi-Way Decisions: Multi-way decision statements involve using “if/else if” statements,
“nested ifs”, or “switch” statments. They are all used to evaluate a logical expression that could have
several possible values. “if/else if” statements are often used to choose between ranges of values.
The form of a mult-way decision using “if / else if” statements is as follows:
if ( logical expression )
stmtT1;
else if ( logical expression )
stmtT2;
else if ( logcial expression )
stmtT3;
.
32 OOPs with C++ Programming
.
.
else if ( logical expression )
stmtTN;
else
stmtF;
If the first logical expression is evaluated to true, then stmtT1 is executed. If the second logical
expression is true, then stmtT2 is executed and so on down the line. If none of the logical expressions
are true, then the statement after “else” is executed which is stmtF.
The form of a multi-way decision using "nested ifs" is as follows:
if ( conditionA )
{
if ( conditionB )
stmtBT;
else
stmtBF;
}
else
stmtAF;
If conditionA is evaluated to true, then execution moves into the nested if and evaluates
conditionB. If conditionA is evaluated to false, then stmtAF is executed.
Example 1:
int x;
if ( x > 0 )
cout << "x is positive" << endl;
else if ( x = 0 )
cout << "x is zero" << endl;
else
cout << "x is negative" << endl;
Example 2:
char ch;
if ( ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' )
cout << "ch contains a letter" << endl;
else if ( ch >= '0' && ch <= '9' )
cout << "ch represents a digit" << endl;
else if ( ch == ' ' || ch == '\t' || ch == '\n' )
cout << "ch is white space" << endl;
else
cout << "ch is a misc. character" << endl;
Control Structures and Loops 33
Switch Statements: A switch statement is yet another option for writing code that deals with
multi-way decisions. I saved it for a section by itself because some programmers feel using a switch
statment is not good programming style. With 1 semester of programming under my belt and a few
years of fooling around with different programming languages, I haven't encountered any problems
with using a switch statement. I haven't written too many programs using switch statments, but when I
have, the programs have seemed to run smoothly. Maybe I'll see why programmers don't like to use
switch statements in later programming experiences. For now, let's explore the ins and outs of a switch
statement.
The following are the feature of a switch construct:
1. Expression must be integer expression.
2. Each case is labelled by integer or character constant.
3. Cases and default may occur in any order.
4. Cases must all be different.
5. After the code for one case is done, execution falls through to the next unless you take
explicit action to escape.
6. The break statement causes an immediate exit from the switch.
7. Falling through cases is a mixed blessing.
8. Positive side is to have one code for multiple cases, redundancy avoided.
9. Negative side is to put break after each case.
Switch statments offer an alternative to an "else if" structure which has multiple possible paths
based on the value of a single expression. A revised form for a switch statement is as follows:
switch (int expression)
{
case label - 1:
stmt-list-1;
break;
case label - 2:
stmt-list-2;
break;
case label - 3:
stmt-list-3;
break;
.
.
.
case label - n:
stmt-list-n;
break;
default:
stmt-list;
}
34 OOPs with C++ Programming
During execution, the expression is evaluated. If the value of the expression matches label - 1,
then stmt-list-1 will be executed. If not, execution will move on to check label - 2 and so on. If no
labels match the expression, default will be executed. Inside each case and at the end of every
statement list (except default) there must be a break statement, which terminates the innermost
enclosing switch or loop statement.
Here are some final notes about switch statements: the expression being tested must result in an
integral value (int or single char), case labels must be integral constants (either literals or
named constants), each label within a switch should be unique, and each stmt-list may contain 0
or more stmts which do not need to enclosed with curly braces { }.
Example:
Suppose a variable named score is an int variable that contains the number of points scored on a
football play. Consider the following code:
switch ( score )
{
case 1 : cout << "Extra Point" << endl;
break;
case 2 : cout << "Safety of two point conversion" << endl;
break;
case 3 : cout << "Field Goal" << endl;
break;
case 6 : cout << "Touchdown" << endl;
break;
default : cout << "Invalid score on a football play." << endl;
}
With selection statements out of the way, it's time to talk about iteration (or looping) in a
program. This, of course, involves using loop statements. Read on to explore the world of looping...
Syntaxes of Selection Statements
Selection (if, if –else)
if Statement
//----- if statement with a true clause
if (expression) {
statements // do these if expression is true
}
//----- if statement with true and false clause
if (expression) {
statements // do these if expression is true
} else {
statements // do these if expression is false
}
Control Structures and Loops 35
cout << "Enter an integer value (between -10 and 10): ";
cin >> k;
}
Example 3:
Write a section of code that will display all multiples of 5 that are less than 500.
int x = 5;
while ( x < 500 )
{
cout << x << endl;
x = x + 5;
}
That wraps up all I have to say about while loops so let's move on to the next loop of interest.
Read on for more about do while loops...
Do While Loops: A do while loop is another type of repetition statement. It is exactly the same
as the while loop except it does something and then evaluates the logical expression of the loop to
determine what happens next. Normally with a while loop, a part of the logical expression in the loop
must be initialized before execution of the loop. A do while loop lets something be performed and then
checks the logical expression of the loop. I like to use a do while loop when using data validation
during a program. The form of a do while loop is as follows:
do
stmt(s);
while ( logical expression );
The stmt in the loop may be single or complex. Complex statements must be enclosed with curly
braces { }. Let's look at a couple of examples of do while loops.
Example 1:
int number;
do
{
cout <<"Enter a postive number greater than 0:";
cin >> number;
}
while ( number <= 0 || int(number) != number );
Example 2:
int number;
do
{
cout << "Enter a number between 0 and 100: ";
cin >> number;
}
while ( number <= 0 || number >= 100 );
38 OOPs with C++ Programming
Having discussed while and do while loops, there is one more loop I would like to cover: for
loops. Read on for more about for loops...
For Loops:
A for loop is another way to perform something that needs to be repeated in C++ (repetition).
Most programmers like to use for loops because the code can be written in a more compact manner
compared to the same loop written with a while or do while loop.. A for loop is generally used when
you know exactly how many times a section of code needs to be repeated. The general form of a for
loop is as follows:
for ( expression1; expression2; expression3 )
stmt(s);
where stmt(s) is a single or compound statment. Expression1 is used to initialize the loop;
expression2 is used to determine whether or not the loop will continue; expression3 is evaluated at the
end of each iteration or cycle.
Note 1: Expression2 is tested before the stmt and expression3 are executed; it is possible that the body of the loop is
never executed or tested.
Note 2: Any or all of the 3 expressions in a for loop can be omitted, but the 2 semi-colons must remain. If expression1
is omitted, there is no initialization done in the loop, but you might not need any initialization for your program.
If expression2 is omitted, there is no test section so you will essentially have an infinite loop. If expression3 is
omitted, there is no update as part of the for statement, but the update could be done as part of the statement in
the body of the loop.
In general, a for loop can be written as an equivalent while loop and vice versa.
for (expression1; expression2; expression3)
stmt;
is equivalent to...
expression1;
while (expression2)
{
stmt(s);
expression3;
}
Example 1: Write a for loop that will display all odd integers between 1 and 51:
for (int k = 1; k <= 51; k += 2)
cout << k << endl;
Example 2: Write a for loop that will display a "countdown" of integers from 20 to 1:
for (int k = 20; k >= 1; k--)
cout << k << endl;
Syntaxes of all loops:
Loop Statements
while Statement: do Statement:
The while statement tests an expression. If the expression This is the least used of the loop statements,
evaluates to true, it executes the body of the while. If it is false, but sometimes you want a loop that
Control Structures and Loops 39
execution continues with the statement after the while body. executes one time before testing.
Each time after the body is executed, execution starts with the do {
test again. This continues until the expression is false or some statements
other statement (break or return) stops the loop.
} while (testExpression);
while (testExpression) {
statements
}
for Statement: Other loop controls:
Many loop have an initialization before the loop, and some break; // exit innermost loop or switch
"increment" before the next loop. The for loop is the standard continue; // start next innermost loop
way of combining these parts. iteration
for (initialStmt; testExpr; incrementStmt) {
statements
}
This is the same as: Function Return:
initialStmt; return; //return no value from void function
while (testExpr) { return expr; //return value of expr from
statements function
incrementStmt
}
3 Functions in C++
Chapter
Chapter Outline
3.1 Introduction to Functions
3.2 Call by Value and Call by Reference
3.3 Function Overloading
3.4 Inline Function
3.5 Functions with Default Arguments
cin>>x;
natural (x); ‘function Call
getch( );
}
void natural (int n)
{ ‘function definition
for(int i=1; i<=n; i++)
{
cout<<i;
}
}
6. Write a program to print natural numbers from lower limit and upper limit through function.
void main( )
{
void natural (int l, int u); ‘function declaration
int l1, u1;
cout<< “enter lower limit & upper limit of natural numbers” <<endl;
cin>>l1>>u1;
natural (l1, u1); ‘function Call
getch( );
}
void natural (int l, int u)
{
for(int i=l; i<=u; i++) ‘function definition
{
cout<<i;
}
}
7. Write a program to print whether number is prime or not using function.
void main( )
{
void prime (int n); ‘function declaration
int x;
cout<< “enter a no”;
cin>> x;
prime (x); ‘function Call
getch( );
}
Functions in C++ 47
In this formal parameters of function definition become aliases to the actual arguments in the
calling function.
Function declaration:
int sum (int * a; int * b);
Function call:
s = sum (& x, & y);
Function definition:
int sum (int * a, int * b)
{
int t;
t = * a + * b;
return t;
}
}
void swap (int a, int b)
{
int temp;
temp=a; ‘function definition
a=b;
b=temp;
cout<<“a=”<<a<<endl;
cout<<“b=”<<b;
}
void swap (float f1, float f2)
{
float temp;
temp=f1; ‘function definition
f1=f2;
f2=temp;
cout<<“f1=”<<f1<<endl;
cout<<“f2=”<<f2;
}
void swap (char c1, char c2)
{
char temp; ‘function defintion
temp=c1;
c1 = c2;
c2=temp;
cout<<“c1=”<<c1<<endl;
cout<<“c2=”<<c2;
}
3. Write a program to print area of circle and area of rectangle using area function with
function overloading.
void main( )
{
int radius, length; breath, arect; ‘variable declaration
float acir;
float area(int r)
‘function declaration
void swap(int l, int b)
cout<<“enter radius”<<endl;
cin>> radius;
Functions in C++ 51
Example:
inline int sum (int a, int b)
{
return (a+b);
}
4. Write a program to print sum of 2 numbers using inline function.
inline int sum (int x, int y), Inline function definition
{
return (x + y);
}
void main( )
{
int a, b, s; ‘variable declaration
cout<<“enter value of a&b”<<endl;
cin>>a>>b;
s=sum (a, b); ‘function Call
cout<<“The sum of 2 Nos is”<<s;
getch( );
}
5. Write a program to print area of circle using inline function.
inline float area (int r)
{
return (3.1415 * r * r); ‘Inline function definition
}
void main( )
{
int radius;
float acir; ‘variable declaration
cout<<“enter radius”<<endl;
cin>>radius;
acir=area(radius); ‘function Call
cout<< “The area of circle is”<<acir;
getch( );
}
3. Whenever the function call is made without specifying the arguments the compiler checks in
the function prototype statement, how many number of arguments are there, hence after
matching the arguments it will automatically assign the values from the default function
prototype declaration.
4. A default argument is checked for type at the time of declaration and evaluated at the time of
call.
5. The default parameters is to be given from the trailing edge to leading edge i.e. from Right to
Left.
6. We cannot provide a default value to a particular argument in the middle of an argument list.
7. We cannot provide a default value from left to right.
8. More than one parameter can have default values.
9. All the parameters of the function can have default values.
10. Some examples of function declaration with default values are:
int sum(int i, int j=5, int k=12); // valid
int sum(int a=5, int b); // notvalid (invalid)
int sum (int x, int y=6, int z); //Invalid
int sum (int x=6, int y=7, int z=8); //valid
11. Default values are not be provided in the function definition.
2. Write a program to print simple interest where rate of interest should be default value.
void main( )
{
float interest(int p, int n, int r=10); ‘function declaration with default values
int pr, nyears;
float si;
cout<<“enter principle amount and number of years” <<endl;
cin>>pr>>nyears;
si=interest (pr, nyears); ‘function Call
cout<<“The simple interest is”<<si;
getch( );
}
float interest (int p, int n, int r)
{
float s; ‘function definition
s= p* n* r/100.0
return s;
}
3. Write a program to print factorial of a number where number should be default value.
void main( )
{ long factorial (int n=5); ‘function declaration with default value
int x;
long f;
f=factorial ( ); ‘function Call
cout<<“The factorial of a no is”<< f;
getch( );
}
long factorial (int n)
{ ‘function definition
long fact = 1;
for (int i=1; i<=n; i++)
{
fact=fact*i;
}
return fact;
}
Functions in C++ 55
4 Classes and Objects
Chapter
Chapter Outline
4.1 Structures of C Language
4.2 Structures and Classes
4.3 Specifying (Defining) a Class
4.4 Defining Member Functions
4.5 Examples of C++ Programs with Class
4.6 Making an Outside Function (Inline)
4.7 Nesting of Member Functions
4.8 Private Member Functions
4.9 Array within a Class
4.10 Static Data Members
4.11 Static Member Functions
float salary;
};
struct employee e;
E is instance variable of type student three member variable are defined by the template. Member
variables can be accessed using the dot or period operator.
Example:
[Link]=10
[Link]=”Kiran”
[Link]=16000
Limitations of Structures:
1. By default members of structures are public hence they do not permit data hiding.
2. Structure does not support inheritance.
3. Member functions can not be encapsulated in a structure.
4. In structures, the instance of the structures can not be added or subtracted.
5. To overcome limitations of the structure class is invented in C++.
6. Structure data type is not treated as built-in data type.
Private area
Data
entry is no t
allow ed M em bers
Public area
Data
entry is
allow ed M em bers
Example:
Class Item
{
Private:
int productid;
float price;
void stock();
Public:
float amount;
void getitem();
void calculate();
void display();
};
In this data member’s productid and price can be accessed by stock, getitem, calculate and
display member functions.
60 OOPs with C++ Programming
i.e., private data members can be accessed by private member functions and public member
functions of a class and data member amount in public can be used outside the class.
i.e., public data members can be used by member functions of a class as well as functions outside
the class.
Creating Objects
Object is a instance variable or class variable. Once the class has been declared, we can create
object of the class i.e. we can create variables of that type by using the class name.
Example:
item x;
item is a class, x is the object or instance of type item x is a variable of class type we can declare
more than one object of a class.
item x, y, z;
This statement create three objects x, y, z. The necessary memory space is allocated to an object.
Accessing Class Members
1. Private data of the class can not be accessed outside the class. It can be accessed only by the
member functions of that class.
2. The public variable and public member functions can be accessed outside the class by
referring [Link](list of arguments);
[Link]();
obj is the object & getdata() is the member function accessed with the help of object. If
member function is parameterised then while calling parameters are to be passed.
Example:
[Link](2,3,5);
obj is the object, calculate is a member function. 2,3,5 are the value of the arguments of the
function.
3. If x is private data member & to access in main function if you have written.
obj.x=10; // It is not allowed
It gives error because private data members cannot be accessed outside the class.
If it is public data member then it can be accessed outside the class.
It x is public variable then we can write.
obj.x=100;
Hence x is assigned as 100.
class student
{
private:
int rollno, marks;
char name [10];
public:
void getdata()
{
cout<<”enter rollno, name & marks of the student” << endl;
(in>> rollno>>name>>marks;
}
void putdata()
{
cout<< “The Rollno is” << rollno <<endl;
cout<< “The name is” << name <<endl;
cout<< “The marks is” <<marks;
}
};
void main()
{
student s;
[Link]();
[Link]();
getch();
}
Example 2: Write a program in C++ to create a class Bank having private data members Accno
for Accountno, balance amt, initial deposit amount.
Provide getdata member function to accept account and initial deposit amount from the user and
make this initial deposit amount as balance.
Provide deposit member function to deposit the amount and according update the balance.
Provide withdraw member function to allow the user to withdraw amount, while withdrawing we
have to check the withdraw amount should be less than balance amount. If it is so allow the user to
withdraw amount and update the Balance else provide message to the user accordingly.
Provide display member function to display account no and balance amount.
# include <iostream.h>
# include <conio.h>
class bank
{
private:
64 OOPs with C++ Programming
[Link]();
[Link]();
[Link]();
getch();
}
Example 3: Write a program in C++ print greatest of three numbers by accept 3 numbers
through getdata and print greatest number through calculate member function.
# include <iostream.h>
# include <conio.h>
Class greatest
{
private:
int a, b, c;
public;
void getdata()
{
cout<<”enter three number “<<endl; cin>>a>>b>>c;
}
void calculate()
{
if (a > b && a > c)
{
cout<<a<< “is greater”;
}
if (b > a && b > c)
{
cout<< b << “is greater”;
}
if (c > a && c > b)
{
cout <<c << “is greater”;
}
}
}
void main()
{
greatest g;
[Link]();
[Link]();
getch();
}
66 OOPs with C++ Programming
Example 4: Write a program in C++ to print factorial of a number, Accept number through
getdata member function, calculate factorial through calculate member function and display factorial
through display member function.
Class factorial
{
private:
int n, fact;
public:
void getdata()
{
count<< “enter a number “<< end; Cin>> n;
}
void calculate()
{
fact = 1;
for (int i = 1; i< = n; i++)
{
fact=fact *i;
}
}
void display()
{
cout<< “the factorial of “<<n <<” is” << fact;
};
void main()
{
factorial f;
[Link]();
[Link]();
[Link]();
getch();
}
Example 5: Program to accept product id, Quantity and price of product through parameterised
getdata member function, calculate total amount through calculate member function and display all
detail through display member function.
# include<iostream.h>
# include<conio.h>
class product
{
private:
int pid, quantity;
Classes and Objects 67
x=a;
y=b;
}
void calculate()
{
m=(a+b)/2.0;
}
void display()
{
cout<<”The mean value is”<<m;
}
};
void main()
{
mean m;
[Link](2,5);
[Link]();
[Link]();
getch();
}
Example 7: Write a program to calculate factorial of a number, through parameterised member
function.
class factorial
{
Private:
int n, fact;
Public:
void getdata(int x)
{
n=x;
}
void calculate();
void display()
{
cout<<”The factorial of”
<<n<<”is”<<fact;
}
};
void factorial :: calculate()
Classes and Objects 69
{
fact=1;
for(int i=1; K=n; i++)
{
fact=fact * i;
}
}
void main()
{
factorial f;
[Link](5);
[Link]();
[Link]();
getch();
}
[Link](100);
[Link](200);
[Link](300);
cout<<”After reading data”;
[Link]();
[Link]();
[Link]();
getch();
}
Arrays, Pointers
5 and References
Chapter
Chapter Outline
5.1 Arrays of Objects
5.2 Objects as Function Arguments
5.3 Friend Function or Friendly Function
5.4 Common Friend Function Between Two Classes or (A Function Friendly to Two Classes)
5.5 Granting Friendship to Other Class
class employee
{
int empno, sal;
char name[10];
public:
void getdata()
{
count <<”enter empno,name & salary”;
cin>>empno>>name>>sal;
}
void display()
{
cout<<”The empno is”<<empno<<endl;
cout<<””The name is”<<name<<endl;
cout<<”The salary is”<<slary<<endl;
}
};
void main()
{
employee e[10];
for (int i=0; i<10; i++)
{
e[i].getdata();
}
cout<<”\n”;
for(int j=0; j,10; j++)
{
cout<<”employee”<<j+1
<<”Details are”<<endl;
cout<<e[i].display();
}
getch();
}
Output:
enter empno name & slary
10 tenna 15000
enter empno name & salary
11 Meena 19000
78 OOPs with C++ Programming
}
void sum(time t1, time t2)
{
minutes=[Link]+[Link];
hours=minutes/60;
minutes=minutes%60;
hours=hours+[Link]+[Link];
}
};
void main()
{
time obj1, obj2, obj3;
[Link](2,45);
[Link](3,30);
[Link](obj1,obj2);
cout<<”obj1=”;
[Link]();
cout<<”obj2=”;
[Link]();
cout<<”obj3=”;
[Link]();
getch();
}
Output:
obj1 = 2 hours and 45 minutes
obj2 = 3 hours and 30 minutes
obj3 = 6 hours and 15 minutes
ob [Link] urs ob [Link] urs ho urs
2 3 6
ob j1.m inu tes ob j2.m inu tes m inu tes
45 50 15
(ob j3) =
ob j1 + obj2
2. If direct access is required then private variables has to be written in public section but it
removes the concept of data hiding. To solve this problem the friend function can be
declared to have an access of private data members of the class.
3. Such a friend function need not be a member of any of these classes.
4. Friend is a special mechanism for non-member function to access private data of a class.
5. Friend function is declared or defined within the scope of class definition.
6. The function should have prefix keyword as friend. This keyword friend informs to the
compiler that it is not a member function of the class but because of friendly this function
can access all data members and member functions of a class.
7. The friend function can be declared with friend keyword as prefix followed by the return
type of the function with function name and arguments of the function.
8. If friend function is declared within a class and defined outside the class then friend keyword
should not be repeated while defining outside the class along with that number :: (scope
resolution operator) is to be used.
9. The Syntax of friend function is
class xyz
{
private:
int a;
public:
__________
__________
friend void display(xyz & x)
{
cout<<”The value of x is”<<x.a;
}
}
10. A friend function, although not a member function, has full access right to the private
member of the class.
Special Characteristics of friend function:
1. It is not in the scope of the class to which it has been declared as friend.
2. A friend function which is not the member function of the class but has full access rights to
the private members of the class.
3. While defining friend function no scope resolution is required.
4. friend function can be declared either in the public or the private part of a class without
affecting its meaning.
5. Normally the member function of a class can access private data members without creating
object but the friend function cannot access the private data member directly but it can be
accessed with object of the class.
Arrays, Pointers and References 81
6. While defining or declaring friend function, the friend function should have argument which
should be object of the class.
7. While calling friend function in the main function. It should have argument which is object
of the class. This function cannot be called with reference to object.
8. friend functions are used in operator overloading.
Example 3: Write a program in C++ to accept two numbers through getdata() member
function and print mean value of two numbers through friend function.
class sample
{
int a,b;
public:
void getdata()
{
cout<<”enter value of a&b”;
cin>>a>>b;
}
friend float mean(sample s);
};
float mean (sample s)
{
return(float (s.a + s.b)/2.0);
}
void main()
{
sample s1;
[Link]();
cout<<”Mean Value is”<<mean(s1);
getch();
}
{
private:
int x;
public:
inline void getdata()
{
cout<<”enter value of x”;
cin>>x;
}
friend int sum(first, second);
};
int sum(first one, second two)
{
int temp;
temp=one.x+two.y;
return temp;
}
class second
{
private:
int y;
public:
inline void getdata()
{
count<<”enter value of y”;
cin>>y;
}
friend int sum(first,second);
};
void main()
{
first a;
second b;
[Link]();
[Link]();
int t = sum (a,b);
cout<<”The sum of 2 Nos is”<<t;
getch();
}
Arrays, Pointers and References 83
Example 5: Write a program to create a common friend of two classes as max which is used to
calculate the maximum number entered by two classes.
private: class abc; //forward declaration
class xyz
{
int x;
public:
void getdata(int i)
{
x=i;
}
void display()
{
cout<<”The value of x is”<<x;
}
friend void max(abc, xyz);
};
class abc
{
private:
int y;
public:
void getdata(int p)
{
y=p;
}
void display()
{
cout<<”The value of y is”<<y;
}
friend void max (abc, xyz);
};
void max(abc e, xyz f)
{
if(e.x>f.y)
{
cout<<e.x<<”is greater than”<<f.y;
}
else
84 OOPs with C++ Programming
{
cout<<f.y<<”is greater than”<<e.x;
}
}
void main()
{
abc a;
xyz b;
[Link](10);
[Link](20);
[Link]();
[Link]();
max(a,b);
getch();
}
Example 6: Write a program to print area of circle through one friend function and area of
rectangle through another friend function.
class area
{
private:
int l,b,r;
public:
void getdata()
{
cout<<”enter length & breadth”<<endl;
cin>>l>>b;
cout<<”enter radius”<<endl;
cin>>r;
}
friend float areac(area a)
{
return(3.1415*a.r*a.r);
}
friend int arear(area b1)
{
return(b1.l*b1.b);
}
};
void main()
Arrays, Pointers and References 85
{
area obj;
[Link]();
cout<<”The area of circle is”<<areac(obj);
cout<<”The area of rectangle is”
<<arear(obj);
getch();
}
{
first objx;
second objy;
[Link]();
[Link](objx);
getch();
}
Example 8: Write a program to create a friendship between two classes. Accept semester1 total
marks through class first and Accept semester2 total marks through class second and print sum of both
semesters.
class first
{
friend class second;
private:
int seml;
public:
void getdata()
{
cout<<”enter total marks of sem1”;
cin>>sem1;
}
};
class second
{
private:
int sem2;
public:
void getdata()
{
cout<<”enter semster2 marks”;
cin>>sem2;
}
void disp(first temp)
{
int sum;
sum=tem.sem1+sem2;
cout<<”The sum is”<<sum;
}
};
Arrays, Pointers and References 87
void main()
{
first objx;
second objy;
[Link]();
[Link]();
[Link](objx);
getch();
}
Constructors
6 and Destructors
Chapter
Chapter Outline
6.1 Introduction to Constructor and Destructor
6.2 Constructors
6.3 Parameterised Constructors
6.4 Multiple Constructors (Constructor Overloading)
6.5 Constructor with Default Arguments
6.6 Copy Constructor
6.7 Dynamic Constructors
6.8 Destructors
6.1 Introduction
We have used member functions such as getdata( ) or input( ) to initialize the variables. When
this function is invoked with the help of object, it assigns the initial values to the data items of object.
These functions invoked when already objects are created. These functions cannot be used to initialize
member variables at the time of creation of their objects hence to perform initialization of members
while creating object is performed by special member function in c++ called constructor.
It is required to be destroy the variable automatically by the compiler, when a variable of built-in
type goes out of scope hence in C++ directly it is not possible.
Hence special member function called the constructor which enables an object to initialize itself
when it is created. This is known as automatic initialization of objects. It also provides another
member function called the destructor that destroys the objects when they are no longer required.
6.2 Constructors
Definition: A constructor is a special member function which enables object to initialize itself
when it is created. It is invoked automatically having same name as the name of the class.
Constructors and Destructors 89
x=o;
}
void display ()
{
cout<< “The x value initialize to” <<x;
}
}; // class declaration ends
void main( )
{
hello hi; //object h1 is
[Link]( ); created and constructor
getch( ); is called
}
Output:
Constructor is called
The x value initialize to 0.
Examples:
1. Write a program to print how many number of objects are created by the user.
int count = o;
class hello
{
private:
int x; //private data members declaration
public:
hello() // constructor
{
count=count + 1;
cout<< “object created no is” << count;
}
};
void main( )
{
hello. h1, h2, h3;
getch( );
}
Output:
Object Created no is 1
Object Created no is 2
Object Created no is 3
Constructors and Destructors 91
2. Write a program to accept the value of x and y from the user through constructor and print
sum of two numbers.
class addition
{
private:
int x, y, sum; //private declaration
public:
addition( ) //constructor
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
void calculate( )
{
sum=x + y;
class addition
{
private:
int x, y, sum; //private declaration
public:
addition( ) //constructor
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
void calculate( )
{
sum=x + y;
}
void display( )
{
cout<< “The sum of 2 Nos is” <<sum;
}
};
void main( )
{
addition a; //object creation
[Link] ( );
[Link]( );
getch( );
}
92 OOPs with C++ Programming
3. Write a program to print sum of even numbers from 1 to n by initializing sum variable to
zero.
class series
{
private:
int n, sum;
public:
series( ) //constructor
{
sum=0;
cout<< “enter value of n”;
cin>>n;
}
void calculate( ); //member function declaration
void display( ) //member function definition
{
cout<< “The sum of even series is” <<sum;
}
};
void series:: calculate( ) //member function definition outside the
class with SCOPE Resolution operator (::)
{
for (int i=2; i<=n; i+ = 2)
{
cout<<i;
}
}
void main( )
{
series s; //creating object
[Link]( );
[Link]( );
getch( );
}
Constructors and Destructors 93
3. Write a program to create a class book to accept bookno, bookname, title, price of the book.
Also accept Quantity to purchased through parameterised constructor. Calculate member
function will calculate total amount to be paid. Display function will display total amount.
class book
{
int bookno, quantity;
char *name; //private declaration
char *title;
double price, amount;
public:
book(int b, char * n, char *t, double p, int Q)
{ //parameterised constructor
bookno=b;
slrcpy (name, n);
slrcpy (title, t);
price=p;
Quantity = Q;
}
void calculate ( )
{
amount = Price * Quantity;
}
void display( )
{
cout<< “The total amount is” <<amount;
}
};
void main( )
{
book b(101, “C programming”, “Complete Reference C”, 400, 2);
[Link]( ); //creating object of parameterised constructor
[Link]( );
getch( );
}
2. Parameterised Constructor: In this, the function call the appropriate values. Number of
parameterised passed within constructor.
3. Copy Constructor: Copy constructor is used to declare and initialize an object from another
object.
Example of constructor overloading
We have two kinds of constructors:
1. try( ) // No arguments
2. try(int, int) // Two arguments parameterised constructor.
In the first, the constructor itself supplies the data values and no values are passed by calling
program.
In the second case, the function call passes the values from main function.
C++ allows us to use both types of constructors in the same class.
class try
{
private:
int x, y, z; //private data member declaration
public:
try( ) //default constructor to initialise data members
{
x=0;
y=0;
z=0;
}
try (int a, int b) //parameterised constructor
{
x=a;
y=b;
}
try (int a, int b, int c)
{
x=a; //parameterised constructor
y=b;
z=c;
}
try(try & i) //copy constructor
{
x=i.x;
y=i.y;
z=i.z;
}
Constructors and Destructors 97
int bookno;
char *name;
char *title;
float price;
public:
book( )
{
bookno=0;
name=’\0’;
title=1\0; title = ‘\0’;
price=0.0;
}
book (int b, char * n, char *t, float p) //parameterised constructor
{
bookno=b;
strcpy (name, n);
strcpy (title, t);
price=p;
}
void display( ) //display member function definition
{
cout<< “The bookno is” <<bookno<<endl;
cout<< “The bookname is” <<name<<endl;
cout<< “The booktitle is” <<title<<endl;
cout<< “The book price is” <<price<<endl;
}
};
void main( )
{
book b; // creating object of default constructor
book b1(100, “cplus”, “Vipul Cplus”, 150.50); //creating object of
parameterised constructor
[Link]( );
getch( );
}
Output:
The bookno is 100
The bookname is Cplus
The booktitle is Vipul cplus
The bookprice is 150.50
Constructors and Destructors 99
6.8 Destructors
1. A destructor is a special member function used to destroy the objects that have been created
by a constructor.
2. After the use of an object, the memory should be deallocated which is holding the object for
this reason the object should be destroyed.
3. Destructor is automatically invoked when the object is not used.
4. Destructor member function is having the same name as a name of destructor and it is
prefixed by ∼ (tilde) sign.
e.g. ∼ test( )
{
}
5. Destructor member function is implicilitly called by the compiler upon exit from the
program by calling delete operator to clean up storage that is no longer accessible.
6. A destructor never takes any arguments.
7. A destructor does not return any value.
8. Since no parameters can be passed, hence destructor can not be parameterized and it cannot
have default arguments.
9. Destructors cannot be overloaded.
10. Destructors cannot be inherited further.
Example 4:
# include <iostream.h>
int count = 0; //declaring global count variable by initializing to zero
class hello
{
public:
hello( )
{ // constructor
count++;
cout<<”object Number created is” << count;
}
∼ hello ( )
{ // destructor
cout<< “No. of object destroyed is” <<count;
count – –;
}
};
void main( )
Constructors and Destructors 105
{
hello h1, h2, h3;
getch( );
}
Output of the program is:
No. of object created is 1
No. of object created is 2
No. of object created is 3
No. of object destroyed is 1
No. of object destroyed is 2
No. of object destroyed is 3
Chapter
Chapter Outline
7.1 C++ Streams
7.2 C++ Stream Classes
7.3 Unformatted I/O Operations
7.4 Formatted Console I/O Operations
7.5 Managing O/P with Manipulators
In put device
extraction from
in put stream
Pro gram
ou tpu t stream in sertion in to
ou tpu t device ou tpu t stream
Manipulators 107
The data in the input stream can come from the keyboard or any other storage device and the
output stream can go to the screen or any other storage device. A stream acts as a interface between
the program and the input/output device. cin represents the input stream connected to the standard
input device.
cout represents the output stream connected to the standard output device.
The default input device for cin is keyboard.
The default output device for cout is screen.
We can Redirect streams to other devices or files also.
po inter
in put
io stream
ios is the base class for istream(input stream) and ostream(output stream), in turn base classes for
iostream(input-output stream).
ios is declared as virtual base class so that only one copy of its members are inherited by the
iostream.
int a,b;
cin>>a>>b;
cout
Example:
cout<<”hello”<<endl;
cout<<”welcome”<<”\n”;
cout<<”Intro to c++ streams”;
Example:
int a,b,sum=45;
cout<<”the sum of 2 Nos is”<<sum;
istream is the input stream.
It inherits the properties of ios
Declares input functions such as get(), getline() and read()
Contain overloaded extraction operator >>
ostream is the output stream.
Inherits the properties of ios
Declares output functions put() and write()
Contains overloaded insertion operator<<
iostream is input/output stream.
Inherits the properties of ios stream and ostream through multiple inheritance and thus
contains all the input and output functions.
streambuf is stream buffer class.
Provides an interface to physical devices through buffers.
Acts as a base for filebuf class used ios files.
put() and get() functions
The istream and ostream classes defines two member functions get() and put() respectively to
handle the single character input/output operations. We can use get (char*) and get(void) prototypes to
fetch a character including blank spaces, tabs and newline characters.
char c;
[Link](c); //ger character from keyboard
while(c !=’\n’)
{
cout<<c; //display a character
[Link](c); //get another character
}
Example :
char c;
c=[Link]();
Manipulators 109
Example 1:
#include<iostream>
#include<string.h>
void main()
{
char*string1=”Kiran”;
char*string2=”Chirag”;
int m=strlen(string1);
int n=strlen(string2);
for(int i=1; i<n; i++)
{
[Link](string2, i);
cout<<endl;
}
for(i=n; i>0; i--)
{
[Link](string2, i);
cout<<”\n”;
}
// concatenating strings
[Link](string1,m).write string2,n);
//crossing the boundary
[Link](string1,3);
getch();
}
Output of program:
C
Ch
Chi
Chir
Chira
Chirag
Chira
Chir
Chi
Ch
C
KiranChirag
Kir
Manipulators 111
3. fill() To specify a character that is used to fill the unused portion of a field.
4. setf() Used to specify format flags that can control the form of output display.
5. unself() To clear the flags specified.
Defining field width:
width() function is used to define the width of a field necessary for the output of an item.
To invoke cout function is used.
[Link](w);
where w is the field width (number of columns).
The output will be printed in a field of w characters wide at the right end of the field.
[Link](5);
cout<<543<<12<<”\n”;
output
54312
setting precision:
Floating numbers are printed with six digits after the decimal point. We can specify the number
of digits to be displayed after the decimal point while printing the floating point numbers.
[Link](d);
[Link](3);
Example:
float a=3.14159
cout precision(3);
cout<<a;
output=3.142
filling and padding: fill()
fill() function is used to fill the unused positions by any desired character.
This functions used to invoke cout method.
[Link](ch);
where ch represents the character which is used for filling the unused positions.
[Link](‘*’);
[Link](10);
cout<<5250<<”\n”;
Output:
******5250
Example 2:
#include<iostream.h>
void main()
{
Manipulators 113
[Link](‘<’);
[Link](3);
for(int n=1; n<=6; n++)
{
[Link] (5);
cout<<n;
[Link](10);
cout<<1.0/float(n)<<”\n”;
if(n==3)
[Link](‘>’;
}
cout<<”\n padding changed \n”;
cout fill(‘#’);
[Link](15);
cout<<12.345678<<”\n”;
getch();
}
The Output:
<<<<1<<<<<<<<<1
<<<<2<<<<<<0.5
<<<<3<<<<<0.333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
>>>>6>>>>>0.167
Pading changed:
#########12.346
endl function is used to insert new line and flush stream. It is equivalent to “\n”.
Example:
1. cout<<setw(10)<<12345;
b b b b b 12345
b indicates black space.
2. cout<<setw(10)<<setiosflags(ios::left)<<12345;
Example 3: Program illustrates the formatting of the output values using both manipulators and
ios functions.
#include<iostream.h>
#include<iomainip>
void main()
{
[Link](ios::showpoint);
cout<<setw(5)<<”no”<<
setw(15)<<”Inverse_of_n”<<
setw(15)<<”sum_of_terms\n”;
double term, sum=0;
for(int n=1; n<=10; n++)
{
term=1.0/float(n);
sum=sum+term;
cout<<setw(5)<<n
<<setw(14)<<setprecision(4)<<setiosflags
(ios::scientific)<<term
<<setw(13)<<resetiosflags(ios::scientific)<<
sum<<endl;
}
getch();
}
Output:
No. Inverse_of_n Sum_of_terms
1. 1.0000e + 000 1.0000
2. 5.0000e – 001 1.5000
3. 3.3333e - 001 1.8333
4. 2.5000e - 001 2.0833
5. 2.000e - 001 2.2833
6. 1.6667e - 001 2.4500
7. 1.4286e - 001 2.5929
Manipulators 115
Function and Operator
8 Overloading
Chapter
Chapter Outline
8.1 Function Overloading
8.2 Operator Overloading
{
cout << “enter value of x” << endl;
cin>>x;
}
void display( )
{
cout<< “x within first class is” <<x;
}
}
class second
{
private:
int x;
void getdata( )
{
cout<< “enter value of x” <<endl;
cin>> x;
}
void display( )
{
cout<< “The value of x in second class is” <<x;
}
};
void main( )
{
first obj1; ‘creates object of class first
second obj2; ‘creates object of class second
[Link]( ); ‘Invoking getdata member function through obj1
[Link]( ); ‘Invoking display member function
[Link]( ); ‘Invoking getdata with reference to obj2
[Link]( ); ‘Invoking display with reference to obj2
display( ); ‘Invoking main global display member function
getch( );
}
Example 2:
Write a program in C++ to create a class areademo has area member function to calculate area of
rectangle and overloaded with another area member function to calculate area of circle.
Class areademo
{
int r, l, b, a; ‘declaring private data members
118 OOPs with C++ Programming
float ac;
public:
int area (int l1, int b1) ‘Defining area parameterised member function
{
l = l1;
b = b1;
retum l *b;
}
float area (int*r1) ‘refining area member function by overloading previous are
member function
{
r=r1;
return (3.1415*r*r);
}
};
void main( )
{
areademo obj; ‘Creating object of a class
cout<< “The area of rectangle is” << [Link] (2, 3);
cout<< “The area of circle is” << obj. area (5); getch( );
}
Example 3:
Write a program in C++ using addition class has common sum member function to add 2 integer
and 3 float numbers using function overloading.
Class addition
{
int x, y, s; ‘declaring private data member
float fx, fy, fz, fs;
void sum (int x1, int g1) ‘definign sum member function with two integer
paremeters
{
x=x1;
y=y1;
S= x + y;
}
void sum (float f1, float f2, float f3) ‘defining sum member function
with 3 float parameters
{
fx=f1;
Function and Operator Overloading 119
fy=f2;
fz=f3;
fs=fx + fy + fz;
}
void dispint( )
{
cout<< “The sum of integer is” <<s;
}
void dispfloat( )
{
cout<< “The sum of float is” <<fs;
}
};
void main( )
{
addition obj;
[Link] (2, 3);
[Link]( );
[Link] (2.5, 5.6, 9.6);
getch(); obj. disfloat( );
x = –2
y=3 Overloaded values
8. In Unary operator using friend function it should have only one argument which should be
the object of the class. Hence object is to be passed as a argument.
9. Unary operator overloading using friend function.
122 OOPs with C++ Programming
Overloading – operator
class abc
{
int x, y; ‘declaring private data members
public:
abc (int a, int b) ‘Defining parameterised constructor
{
x = a;
y = b;
}
friend void operator – (abc & S)
{ ‘defining operator function as a friend function
s.x = – s.x;
s.y = – s.y;
}
void display( ) ‘ defining display member function
{
cout<< “x =” <<x<<endl;
cout<< “y =” <<y;
}
};
void main( )
{
abc s(2, – 3); ‘creating parameterised object
[Link]( ); ‘invoking display function
– s; ‘overloading ‘–‘ operator
[Link]( ); * invoking display function
getch( );
}
Example 2:
Overloading + operator as a binary operator to add 2 complex numbers by operator as a member
function.
#include <iostream.h>
class complex
{
float x, y;
public:
complex (float real, float, img) ‘constructor
{
x = real;
y = img;
}
complex operator + (complex c) ‘operator function
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return temp;
}
void display( )
{
cout <<x << “+ j” <<y <<endl;
}
};
void main( )
{
complex c1, c2, c3; ‘creating objects
C1 = complex (2.3, 4.5);
C2 = complex (1.3, 1.6);
C3 = c1 + c2; ‘overloading operator
cout << “C1 =”;
cout << [Link]( );
cout << “C2=”;
cout << [Link]( );
cout << “C3 =”;
cout << [Link]( );
getch( );
}
Function and Operator Overloading 127
Example 3:
Overloading + operator as a binary operator to combine two strings by using operator function as
a member function.
#include <iostream.h>
#include <string.h>
class stringdemo
{
char s[10];
public:
stringdemo (char s1[10]) ‘constructor
{
strcpy (s, s1):
}
stringdemo operator + (string demo d) ‘operator function
{
strcat (s, d.s);
return s;
}
void display( ) ‘display function
{
cout<< “combined string is” <<s;
}
};
void main( )
{
stringdemo s1 (“Kiran”); ‘object
stringdemo s2 (“Gurbani”); creation
stringdemo s3;
s3 = s1 + s2; ‘invoking operator function
[Link]( );
getch( );
}
9 Inheritance
Chapter
Chapter Outline
9.1 Introduction to Inheritance
9.2 Types of Inheritance
9.3 Declaring Derived and Base Class
9.4 Single Inheritance
9.5 Multilevel Inheritance
9.6 Multiple Inheritance
9.7 Hybrid Inheritance
9.8 Hierarchical Inheritance
A Base class
B Derived class
2. Multilevel Inheritance: The mechanism of deriving a class from another derived class is
known as Multilevel Inheritance.
A Base class
C Derived class
In multilevel first class is derived from base class and again from derived class another class
will be derived.
3. Multiple Inheritance: A derived class with several base classes, is called multiple
inheritance.
A B
C
This type of inheritance can have one or more base classes from that we can drive only
derived class is called as Multiple Inheritance.
4. Hierarchical Inheritance: The properties of one class may be inherited by more than one
class is called hierarchical Inheritance. In this type of inheritance one base class, number of
classes can be derived is known as hierarchical Inheritance.
B C D
130 OOPs with C++ Programming
B C
# include <iostream.h>
class base
{
int x;
public:
int y;
void getdata( )
{
cout<< “enter value of x&y”;
cin>>x>>y;
}
int getx( )
{
return x;
}
void show x( )
{
cout << “x; is” <<x;
}
};
class d: public base
{
int total;
public:
void sum( )
{
total = y + getx( );
}
void display( )
{
cout<< “x =” << getx( )<<endl;
cout<< “y =” << y <<endl;
cout<< “sum =” <<total;
}
};
void main( )
{
d obj;
[Link]( );
132 OOPs with C++ Programming
[Link]( );
[Link]( );
obj.y=100;
[Link]( );
[Link]( );
getch( );
}
}
};
class d: private base
{
int z;
public:
void setxy( )
{
getxy( );
}
void MUL( )
{
z = y * getx( );
}
void display( )
{
showx( );
cout << “y =” << y;
cout << “z =” << z;
}
};
void main( )
{
d obj;
[Link] ( );
[Link]( );
[Link]( );
getch( );
}
Output:
enter the value of x & y : 5 10
The x value is 5
y = 10
z = 50
derived class but it will also accessed by other classes, hence it removes data hiding concept
so keep those private variables in a protected scope.
2. This third visibility mode protected used for limited access of private data inheritance.
3. A member declared in protected scope of base class can be accessed by only member
functions of derived class. It cannot be accessed by the functions outside these two classes.
4. When a derived class inherited as protected from base class then protected members of base
class will become protected members of derived class and public members of base class will
become protected members of derived class and private members of base class can not be
further inherited.
Class B
Protected
Public
Class D1: Public B Class D2: Public B
Private Private
Protected Protected
Public Public
Class x: Public D1: Protected D2
Private
Protected
Public
A Base class
C Derived class
4. Class B can inherit the properties of A class C can inherit the properties of A&B both.
Example 1:
Create a base class student to accept Rollno and display Rollno through member functions.
Create sem1 derived class to accept total marks of sem1 and print marks of sem1 through member
functions. Create sem2 derived class from sem1 to accept and print the marks of sem2 through
member functions. Create a result derived class to print rollno, sem1, sem2 marks and total marks of
sem1 & sem2.
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll( )
{
cout<< “enter rollno”;
cin>>rollno;
}
void putroll( )
{
cout<< “The Rollno is” << rollno;
}
};
class sem1: public student
{
protected:
int s1;
public:
void getsem1( )
{
cout<< “enter total marks of sem1”;
cin>> s1;
136 OOPs with C++ Programming
}
void putsem1( )
{
cout<< “sem1 marks is” << sem1;
}
};
class sem2: public sem1
{
protected:
int s2;
public:
void getsem2( )
{
cout<< “enter total marks of sem2”;
cin >> s2:
}
void putsem2( )
{
cout<< “sem2 marks is” <<sem2;
}
};
class result: public sem2
{
private:
int total;
public:
void display( )
{
total=s1 + s2;
putroll( );
putsem1( );
putsem2( );
cout << “Total marks is” << total;
}
void main( )
{
result r1;
[Link]( );
r1.getsem1( );
Inheritance 137
r1.getsem2( );
[Link]( );
getch( );
}
Example 2:
Create a class student to accept rollno and print rollno through member functions. Create a
derived class marks to accept marks of three subjects and print three subjects marks. Create a derived
class Result to display total of all 3 subjects and Avg of 3 subjects.
class student
{
protected:
int rollno;
public:
void getroll ( )
{
cout << “enter rollno”;
Cin>> rollno;
}
void putroll ( )
{
cout<< “The Rollno is” <<rollno;
}
};
class marks : public student
{
protected:
int sub1, sub2, sub3;
public:
void getmark( )
{
cout<< “enter 3 subjects marks”;
(Cin>>sub1>>sub2>>sub3;
}
void putmark( )
{
cout<< “Three subjects marks are” << “sub1=”<<sub1<<”sub2=”<<
sub2<<”sub3=”<<sub3;
}
};
class result : public marks
138 OOPs with C++ Programming
{
int total;
float avg;
public:
void display( )
{
total = sub1+sub2+sub3;avg=total/3.0;
putroll( );
putmark( );
cout<< “total marks is” <<total<<endl;
cout<< “The Average marks is” <<avg;
}
};
void main( )
{
result r1;
[Link]( );
[Link]( );
[Link]( );
getch( );
}
C Derived class
3. Multiple Inheritance allows to combine the features of A & B in C hence class C can inherit
the properties of A & B.
4. The syntax is
class D: visibilitymode baseclass 1,
visibilitymode baseclass 2
{
Body of class D;
}
Inheritance 139
D is derived class, derived from two base classes baseclass1 and baseclass2 with visibility
mode can be private, public, protected.
5. Example 1:
Create a base class M to accept and print value of M variable. Create another base class N to
accept and Print value of N variable. Create derived class P from M & N to multiply the
value of M variable and N variable through member functions also display M & N individual
values along with product.
class M
{
protected:
int m;
public:
void getm(int x)
{
m=x;
}
void putm( )
{
cout<< “M value is” <<m;
}
};
class N
{
protected:
int n;
public:
void getn(int y)
{
n=y;
}
void putn( )
{
cout<< “n value is” <<n;
}
};
class P: public M, public N
{
int mul;
public:
140 OOPs with C++ Programming
void display( )
{
mul=m*n;
putm( );
putn( );
cout<< “product is” <<mul;
}
};
void main( )
{
p obj;
[Link](25);
[Link](10);
[Link]( );
getch( );
}
Example 2:
Write a program in C++ to create a base class basic to accept basic salary from the user and
print basic salary. Create another base class year to accept and print number of years worked
in the organisation. Create a derived class from both base classes to print basic sal, no. of
years and check if number of years > =3 then print bonus is 300 and add that bonus to basic
sal. print updated basic and if it is < 3 then bonus = 100 add to basic and print updated basic
through member function.
#include<10stream.h>
class basic
{
protected:
int basic;
public:
void getbasic(int x)
{
basic=x;
}
void printbasic( )
{
cout<< “The basic is” << basic;
}
};
class year
{
Inheritance 141
protected:
int year;
public:
void getyear (int y)
{
year = y;
}
void putyear( )
{
cout<< “The year is” <<year;
}
};
class d: public basic, public year
{
public:
void display( )
{
cout<< “original basic is” <<basic;
cout<< “No. of years is” << year;
if (year >= 3)
{
int bonus=300;
basic = basic + 300;
}
else
{
int bonus=100;
basic = basic + 100;
}
cout<< “Updated basic is” <<basic;
}
};
void main( )
{
d obj;
[Link](5000);
[Link](10);
[Link]( );
getch( );
}
142 OOPs with C++ Programming
Student
Test Sports
Result
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll(int a)
{
rollno=a;
}
void putroll( )
{
cout<< “The rollno is” <<rollno;
}
};
class test: public student
{
protected:
int sub1, sub2;
public:
void getmarks(int x, int y)
Inheritance 143
{ sub1=x;
sub2=y;
}
void putmarks( )
{
cout<< “sub1= “<<sub1 <<endl;
cout<< “sub2= “<<sub2 <<endl;
}
};
class sports
{
protected:
int spmark;
public:
void getsport(int P)
{
spmark = p;
}
void putscore( )
{
cout<< “sports marks is” <<spmark;
}
};
class result: public test, public sports
{
int total;
public:
void display( )
{
total = sub1+sub2+spmark;
putroll ( );
putmarks( );
putscore( );
cout << “The total is” << total;
}
};
void main( )
{
result s;
[Link] (10);
[Link](25, 95);
144 OOPs with C++ Programming
[Link](49);
[Link]( );
getch( );
}
B C D
4. Example:
Create a Base Class student to accept rollno and print rollno through member function.
Create three derived classes art, medical and Engg. In derived class art, accept the marks of
arts and print the art marks. In derived Class Medical marks. Accept medical marks and print
medical marks. In derived class Engg. define member function for mechanical, electrical,
civil to accept the marks and print the marks through dispengg member function. In the main
function give choice to the user to select either of one type from mech, elec, civil. Accept
marks of each and display.
#include <iostream.h>
class student
{
protected:
int rollno;
public:
void getroll( )
{
cout<< “enter rollno” <<endl;
cin>> rollno;
}
void disproll( )
{
cout<< “rollno is” <<rollno;
}
};
class art: public student
Inheritance 145
{
protected:
int marks;
public:
void getart( )
{
getroll( );
cout<< “enter arts marks”;
cin>>marks;
}
void dispart( )
{
disproll( );
cout<< “Arts marks is” <<marks;
}
};
class med: public student
{
protected:
int marks;
public:
void getmedi( )
{
getroll( );
cout<< “enter medical marks” <<endl;
cin>> marks;
}
void dispmedi( )
{
putroll( );
cout<< “Medical marks is” <<marks;
}
};
class engg: public student
{
protected:
int marks;
public:
void mech( )
{
getroll( );
146 OOPs with C++ Programming
case 2:
[Link]( );
break;
case 3:
[Link]( );
break;
}
[Link] ( );
getch( );
}
Virtual Functions
10 and Polymorphism
Chapter
Chapter Outline
10.1 Polymorphism
10.2 Virtual Function
10.3 Rules of Virtual Functions
10.4 Pure Virtual Function
10.5 Abstract Classes
10.6 EARLY Binding
10.7 LATE Binding
10.1 Polymorphism
Compile Time and Run Time Polymorphism:
1. Polymorphism is basic feature of OOPS. It states that one thing behaves differently at
different place.
2. It also states that one name multiple forms i.e., one function name behaves differently for
different tasks.
Same as one operator behaves differently at different place.
3. Polymorphism can be function overloading Or operator overloading.
4. Polymorphism is divided into two parts.
(a) Compile time polymorphism.
(b) Run time polymorphism.
5. Compile time polymorphism: In function overloading and operator overloading the compile
time polymorphism is achieved. In function overloading the function name is same with
different number of parameters or type of parameters it is overloaded. Overloaded member
functions are selected for invoking by matching arguments both type and the number.
Virtual Functions and Polymorphism 149
This information is known to the compiler at compile time and hence compiler is able to
select the appropriate function for a particular call at compile time itself.
This is called compile time polymorphism. This is also called as early binding or static
binding.
Early binding indicates that an object is bound to its function call at compile time.
At the compile time if prototype does not match then compile time error occurs.
The binding of function and allocation of variables during compilation time is called compile
time polymorphism.
6. Runtime polymorphism:
(a) When object is created at Run time and when at Runtime object is bounded to allocate
memory then it is called Runtime polymorphism.
(b) When the base class and derived class have same function with same prototype then
function is not overloaded it is based at Runtime which function is selected for base or
derived. This is called Run time polymorphism.
class base
{
int x;
public:
void show( )
{ _________
_________
_________
}
};
class d: public base
{
int y;
public:
void show( )
{ ________
________
________
}
};
In this example, both base class and derived class has common show( ) member function with
same prototype.
This show function is still not overloaded. Because it is based how it is called at Run time with
the help of object pointer by specifying member function of base class or derived class.
150 OOPs with C++ Programming
This is called Run time polymorphism. The binding performed at Runtime is called late binding
also called dynamic binding because the selection of a particular function is done dynamically at
Runtime.
7. Polymorphism can be graphically represented as follows:
Polymorphism
d obj1;
d1 obj2;
p=&b;
p vfunc( );
p = &obj1;
p vfunc( );
p = &obj2;
p vfunc( );
getch( );
}
Output:
This is base class vfunction
This is derived 1 class vfunction
This is derived 2 class vfunction
};
class d2: public base
{
public:
void show( )
{
cout<< “In Derived2”;
}
};
void main( )
{
Base *a[2];
d1 obj1;
d2 obj2;
a[0] = &obj1;
a[1] = &obj2;
a[0] show( );
a[1] show( );
}
Output:
In Derived 1
In Derived 2
11 File Handling
Chapter
Chapter Outline
11.1 Introduction to File Handling
11.2 Classes for File Stream Operations
11.3 Opening and Closing a File
11.4 Detecting End of File
11.5 More about Open (): File Modes
11.6 File Pointer and their Manipulations
11.7 Sequential Input and Output Operations
11.8 Reading and Writing a Class Object
11.9 Updating a File
11.10 Error Handling During File Operations
11.11 Command-Line Arguments
In put stream
read data
data inp ut
data ou tput
w rite data
File input and output streams
The I/O system uses file streams as an interface between the programs and the files. The stream
that supplies data to the program is known as input stream and the one that receives data from the
program is known as output stream.
The input stream extracts OR reads data from the file and output stream is used to insert or write
data to the file.
The input operation is used to create input stream and this input data link to the program and
output operation involves establishing an output stream. It takes data output from the program to
output stream and writes the data to disk files.
io stream
fileb uf
ifstream fstream ofstream
fstream
file
fstream base
ios is a class consist of istream and ostream class. istream is the input stream class and ostream is
the output stream. fstream base class consist of ifstream and ofstream classes used for creating input
stream and output stream.
iostream class has input stream (Istream) and ostream (output stream).
Streambuf class has filebuf class.
fstream class has ifstream and ofstream. ifstream functions meaning open for reading only.
Ofstream functions meaning open for writing only.
For example:
ofstream outfile (“[Link]”);
ofstream is a class, outfile is a object ofstream class within object parameters. We are specifying
the filename that means we are calling parameterised constructor of ofstream. Hence if we want to
write anything into file, it can be written with the help of outfile object.
Example:
outfile << “Total”;
outfile << sum;
Output:
total 45
if value of sum variable is 45.
Ifstream class is used to create input file stream.
ifstream infile (“[Link]”);
ifstream is a class and infile is a object. Object has a parameter which is filename. If we want to
read anything from the file, we can read through infile object.
Example:
infile >> sum;
Reading value of sum variable from the file [Link].
2. Using the member function Open:
This method is used when we want to manage multiple files using one stream. open() function is
used to open multiple files that use the same stream object. We may need to process a set of files
sequentially.
Example:
ofstream outfile; // creates object for
output stream
[Link](“[Link]”); // opens [Link] file
[Link] // closing a file
[Link](“[Link]”); // opening [Link]
with same object
[Link] // closing a file
Hence with the same object we can open multiple files.
Closing a file The file can be closed with the help of close method. For close method we have
to specify object [Link].
Example:
[Link]
Outfile is an object name, hence with the help of close method, it will close object outfile, in turn
will close the file which is opened through outfile object.
Note: When the file is opened for writing only it means with the help of ofstream class object, a new file is created. If
there is no file existing of the same name. If the same name file is already existing then current contents will be
overwrite the previous contents.
File Handling 159
clrscr();
ofstream out;
[Link](“[Link]”);
out<<“hello”;
[Link]();
ifstream inf;
[Link](“[Link]”);
inf>>name;
cout<<name;
[Link]();
getch();
}
4. Write a program to accept item name and cost of item from the user and write it into the
[Link] file and then display the contents of [Link] file.
void main()
{
char name[20];
float cost;
clrscr();
ofstream out;
[Link](“[Link]”);
cout<<“enter the item name”;
cin>>name;
out<<name<<end1;
cout<<“enter the cost”;
cin>>cost;
out<<cost;
ifstream inf;
[Link](“[Link]”);
inf>>name;
inf>>cost;
cout<<“The item name is”<<name;
cout<<“The item cost is”<<cost;
[Link]();
getch();
}
5. Write a program to accept empno, name and salary of emp. from the user and save it into
[Link] and then display on the screen.
void main()
{
char name[20];
162 OOPs with C++ Programming
[Link](“[Link]”);
while(inf)
{
[Link](x,80);
cout<<x;
}
[Link]();
getch();
}
{
cout<<8etw(10)<<setprecision(2)<<height[i];
}
[Link]();
getch();
}
The output of program is
175.50 153.00 167.25
Example of Reading and writing class objects:
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
class employee
{
int empno;
char name[10];
float salary;
public:
void readdata(void)
{
cout<<“enter empno, name & salary”;
cin>>empno>>name>>salary;
}
void writedata(void)
{
cout<<setiosflags(ios::left)<<setw(10)<<
empno<<name<<salary;
}
};
void main()
{
employee e[2];
fstream file;
[Link](“[Link]”, ios::in|ios::out));
cout<<“enter details of two employees”;
for(int i=0; i<2; i++)
{
e[i].readdata();
File Handling 167
[Link] ((char*)&e[i],sizeof(e[i]));
}
[Link](0);
cout<<“\nOUTPUT\n\n”;
for(i=0; i<2; i++)
{
[Link]((char*)&e[i], sizeof(e[i]));
e[i].writedata();
}
[Link]();
getch();
}
The output of program:
Enter details of two employees.
enter empno, name & salary
1 malcolm 40000
enter empno, name & salary
2 Angela 20000
Output:
1 malcolm 40000
2 Angela 20000
else
{
[Link](); // clear error state
________
________
________
________
}
Check each and every numbered array element. If it is even then write the contents into 2nd file.
Advisable to take the 2nd file name as [Link] and if the number is odd then write that number into
the 1st file advisable to take [Link].
# include<iostream.h>
# include<fstream.h>
# include<stdlib.h>
int main (int argc, char*argv[])
{
int number [10] = {1,2,3,4,5,6,7,8,9,10};
if(argc!=2)
{
cout<<”error in arguments p/s.
enter two arguments”;
exit(1);
}
ofstream fout1, fout2;
[Link](argv[1]);
[Link](argv[2]);
for (int i=0; i<=9; i++)
{
if (number [i] 2 ==0)
{
fout2<<number[i],<<“ ”;
}
else
{
fout1<<number[i]<<“ ”;
}
}
[Link]();
[Link]();
ifstream fin;
char ch;
for (i=1; i<argc; i++)
{
[Link](argv[i]);
cout<<“The contents are”;
while(fin)
{
[Link](ch);
File Handling 171
cout<<ch;
}
[Link]();
}
} return 0;
Output:
contents of odd
1 3 5 7 9
contents of even
2 4 6 8 10
Example:
1. Write a program to display the length of a file
# include<iostream.h>
# include<conio.h>
void main()
{
int count=0;
char ch;
ifstream inf;
[Link](“[Link]”);
while (inf)
{
[Link](ch);
int count = count + 1;
}
count<<”The Length of the file is”<<count;
[Link]();
getch();
}
2. Write a program to read the contents of 1 file & append those contents into another file.
# include<iostream.h>
# include<conio.h>
void main()
{
char ch;
ifstream inf;
ofstream out;
[Link](“[Link]”);
[Link](“[Link]”);
172 OOPs with C++ Programming
while(inf)
{
[Link](ch);
[Link](ch);
}
[Link]();
[Link]();
getch();
}
12 Templates
Chapter
Chapter Outline
12.1 Introduction
12.2 Class Templates
12.3 Class Templates with Multiple Parameters
12.4 Function Templates
12.5 Function Templates with Multiple Parameters
12.6 Overloading of Template Functions
12.7 Member Function Templates
12.8 Non-Type Template Arguments
12.1 Introduction
Template is a method for writing a single function or class for a family of similar functions or
classes in a generic manner. When a single function is written for a family of similar functions, it is
called as ‘function template’.
A template can be used to create a family of classes or functions.
The templates can be for array class, creating arrays of various data types such as integer array,
float array, character array or double array.
{
sum+=thisv[i]*y.v[i];
}
return sum;
}
};
void main()
{
int x[3]={1,2,3};
int y[3]={4,5,6};
vector <int> v1;
vector <int> v2;
v1=x;
v2=y;
int R=v1*v2;
cout<<“R=”<<R<<endl;
getch();
}
The class template definition is similar to ordinary class definition. Only difference is that the
class definition is prefixed by temp <class t>. This prefix tells the compiler that we are going to
declare a template t is a type name in the declaration. Thus the vector becomes parameterised class
with the type t as the parameter. We can create vector for holding different datatypes like the vector
can be int vector or float vector.
A class which is created from a class template is called a template class. If we want to create the
object of template, the syntax is
classname <type> objectname(args list);
OR
classname <type>objectname;
Example:
# include<iostream.h>
template<class T1, class T2>
class test
{
T1 a;
T2 b;
public:
Test(T1 x, T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<“and”<<b<<endl;
};
void main()
{
Test <float,int> test1(1.23,123);
Test <int,char> test2(100,’W’);
[Link]();
[Link]();
getch();
}
Output of program:
1.23 and 123
100 and W
________
________ // body of function with type T wherever
appropriate
}
The function template syntax is similar to that of the class template except that we are defining
functions instead of classes. We must use the template parameter T as and when necessary in the
function body and in its argument list.
Example:
# include<iostream.h>
# include<conio.h>
template<class T>
void swap(T &x, T &y)
{
T temp=x;
x=y;
y=temp;
}
void fun(int m, int n, float a, float b)
{
cout<<“m and n before swap:”<<m<<“ ”<<n<<endl;
swap (m,n);
cout<<“m and n after swap:”<<m<<“ ”<<n<<endl
cout<<“a and b before swap:”<<a<<“ ”<<b<<endl;
swap(a,b);
cout<<“a and b after swap:”<<a<<“ ”<<b<<endl;
}
void main()
{
fun(100,200,11.22,33.44);
getch();
}
Output of the program is
m and n before swap 100 200
m and n after swap 200 100
a and b before swap 11.22 33.43
a and b after swap 33.43 11.22
Program consist of swap() function template that will swap two values of a given type of data.
This template function declares a set of overloaded functions, one for each type of data. We can
invoke or call swap() function like any ordinary function.
178 OOPs with C++ Programming
For example, fun() is ordinary function having four parameters. Within this ordinary function we
can call swap() functions.
Example:
template <class T>
class vector
{
T* V;
int size;
public:
vector (int m);
vector (T* a);
T operator * (vector & y);
};
// member function templates …
template<class T>
vector<T>::vector(int m)
{
v=new T[size=m];
for(int i=0; i<size; i++)
{
v[i]=0;
}
}
template<class T>
vector<T>::vector(T* a)
{
for(int i=0; i<size; i++)
{
v[i] = a[i];
}
}
template<class T>
T vector<T>::Operator * (vector &y)
{
T sum=0;
for(int i=0; i<size, i++)
{
sum+=thisv[i] * y.v[i];
}
return sum;
}
In above program the class vector has member functions which are declared within a class they
are redefined outside class vector. Member functions are parameterised member function.
Templates 181
template<class
AType, int size>
AType & atype<AType,size>::operator[](int i)
{
if(i<0 || i>size–1)
{
cout<<“Index value of”<<i<<“is out of bound”
<<endl;
exit(1);
}
return a[i];
}
void main()
{
atype<int, 10>intob; //integer array of size 10
int i;
cout<<“Integer array”;
for(i=0; i<10; i++)
{
intob[i]=i;
}
for(i=0; i<10; i++)
{
cout<<intob[i]<<“ ”;
}
getch();
}
13 Exception Handling
Chapter
Chapter Outline
13.1 Introduction and Basics of Exception Handling
13.2 Exception Handling Mechanism with Try, Catch & Throw Statement
13.3 Multiple Catch Statements
13.4 Rethrowing and Exception
13.5 Specifying Exception
13.6 Advantages of Exception Handling
13.2 Exception Handling Mechanism With Try, Catch & Throw Statement
An exception is an error or an unexpected event. The exception handler is a set of codes that
executes when an exception occurs.
Exception handling uses basically 3 blocks:
(i) Try (ii) Throw, (iii) Catch.
The try & catch blocks are written between open & closing curly braces ‘{ }’. The try block is
identified by try keyword having block of statements between {and}. When the exception is detected
by the try block, it is thrown using throw statement in try block.
A catch block is defined by the keyword catch followed by { } with block of statement. This
catch block catches the exception thrown by throw statement in try block and handles it appropriately.
When the try block throws an exception the program control leaves the try block and enter into the
catch block and if the type of object thrown by the try block matches then only the catch block is
executed for handling exception. If they do not match, the program is aborted using abort function.
Example:
void main()
{
int a,b;
cout<<“enter value of a & b”;
cin>>a>>b;
int x=a–b;
try
{
if(x!=0)
{
cout<<“Result of division is”<<(a/x);
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<“exception at x=”<<x;
Templates 185
Function that
c aus es a n
e xc eption In vo ke
function
Try block
In vo kes a fu nc tion
tha t c ontain s an
e xception .
Th row
exc eption
Ca tch block
C atch es an d
handles th e
e xc eption
Figure
Syntax (general format of try catch block)
type function (argument list)
{ ________
________
________
________
throw(object) //throw exception
________
________
________
________
}
________
________
________
________
try
{ ________
________
________
186 OOPs with C++ Programming
{
try
{
if(x==1)
{
throw x;
}
else
{
if(x==0)
{
throw x;
}
else
{
if (x==–1)
{
throw 1.0
}
cout<<“end of try block”;
}
catch(char c)
{
cout<<“caught a character”;
}
catch(int m)
{
cout<<“caught an integer”;
}
catch(double d)
{
cout<<“caught a double”;
}
cout<<“end of try catch block”;
}
void main()
{
cout<<“for x=1” <<endl;
test(1);
cout<<“for x=0”<<endl;
test(0);
188 OOPs with C++ Programming
cout<<“for x=–1”<<endl;
test(–1);
cout<<“for x=2”<<endl;
test(2);
getch();
}
{
cout<<“Inside main function”;
try
{
divide(10.5,2.0);
divide(20.0,0.0);
}
catch(double)
{
cout<<“caught double inside the main
function”;
}
cout<<“end of main”;
getch();
}
Example:
void test(int x) throw(int, double)
{
if(x==0) throw ‘x’; // char
else
if(x==1) throw x; // int
else
if(x==–1) throw 1.0; // double
cout<<“end of function block/n”;
}
void main()
{
try
{
cout<<“Testing Throw Restriction”<<endl;
cout<<“x==0”<<endl;
test(0);
cout<<“x==1”<<endl;
test(1);
cout<<“x==–1”<<endl;
test(–1);
cout<<“x==2”<<end1;
test(2);
}
catch(char c)
{
cout<<“caught a character”<<endl;
}
catch(int m)
{
cout<<“caught an integer”<<endl;
}
catch(double d)
{
cout<<“caught a double”<<endl;
}
cout<<“End of try-catch system”;
getch();
}
Templates 191
Output:
Testing Throw Restrictions
x==0
caught a character
End of try-catch system
In above example, test function is called by passing value of x=0, in the test function if the value
of x is zero then it with character ‘x’, catch block catches it and displays a message caught a character
and terminate the loop because in test function with the throw clause type-list specifies only int and
double exception should be thrown but the character is not listed in type-list hence program will be
terminated.
14 Standard Template Library
Chapter
Chapter Outline
14.1 Introduction
14.2 Component of STL
14.3 Containers
14.4 Algorithms
14.5 Iterators
14.6 Applications of Container Classes
14.1 Introduction
Templates are used to create generic classes and functions. Templates are used to create classes
(data structures) and functions (algorithms).
The collection of these classes and function is called Standard Template Library (STL).
STL components are part of standard C++ Library defined in the namespace std.
Hence to include this namespace we can write.
using namespace std;
This statement is like include statement. It indicates to the complier that we want to use standard
C++ library.
STL has three foundational items:
(a) Containers (b) Algorithms (c) Iterators.
Containers are object that hold another objects like vector (dynamic array), deque (double-ended
queue) and linear list.
Algorithms act on containers. They provide the means by which you will manipulate the content
of containers. Here sorting, searching of contents of containers can be done.
Iterators are objects that act, more or less, like pointers.
Standard Template Library 193
iterator 1 iterator 2
object 1 object 2
object 3
iterator 3
Algorithm 3
14.3 Containers
Containers are objects that hold other objects of same type. It contains vector class, defines
dynamic array, deque create double ended queue and list provides a linear list.
The STL defines ten containers which are grouped into three categories
194 OOPs with C++ Programming
Con tainers
Sequence Containers:
Vector is a dynamic array. It allows insertions and deletions at back, permits direct access to any
element. List is linear list, allows insertions and deletion anywhere. deque is double-ended queue,
allows insertions and deletions at both the ends, permits direct access to any element.
Associative Containers:
Set It is an associate container for storing unique sets. No duplication is allowed. It allows
rapid Lookup & Search.
Multiset It is an associate container for storing non-unique sets. (Duplicate allowed)
Map An associate container for storing unique key/value pairs. Each key is associated with
only one value (one-to-one mapping).
Multimap It is an associate container for storing key/value pairs in which one key may be
associated with more than one value (one-to-many mapping). Allows key-based Lookup.
Derived Containers:
1. stack A standard stack LAST IN FIRST OUT (LIFO).
2. queue A standard queue FIRST IN FIRST OUT (FIFO).
3. priority queue A priority queue. The first element out is always the highest priority
element.
(A) Sequence Containers:
(i) Sequence containers store elements in a linear sequence.
(ii) Each element is related to other elements by its position along the line.
(iii) These all elements can expand themselves to allow insertion of elements and number of
operations can be applied.
elem ent 0 elem ent 1 elem ent 2 last elem en t
Iterator
begin() end()
(iv) STL provides three types of sequence containers: (1) vector (2) list (3) deque as already
explained.
(B) Associative Containers:
Associative Containers are designed to support direct assess to elements using keys. They are not
sequential.
Standard Template Library 195
14.4 Algorithms
Algorithms are functions that can be used generally across a variety of containers for processing
their contents.
Each container provides functions for its basic operations.
A standard algorithms provide more extended or complex actions.
In this we can work with two different types of containers at the same time.
STL has different algorithms, and these algorithms are template functions and can be applied to
any type of container.
STL algorithms are categorised as follows:
1. Retrieve or non-mutating algorithms
2. Mutating algorithms
3. Sorting algorithms
4. Set algorithms
5. Relational algorithms
1. Retrieve OR Non Mutating Algorithms:
(a) adjacent_find(): This method finds adjacent pair of objects that are equal.
(b) count(): This method counts occurence of a value in a sequence.
(c) count_if(): It counts number of elements based on condition.
(d) equal(): This method returns true if two ranges are the same.
(e) find(): This method finds first occurence of a value in sequence.
(f) find_end(): This method finds last occurence of a value in sequence.
196 OOPs with C++ Programming
14.5 Iterators
Iterators are like pointers, they are used to access container elements. These pointer while
accessing container elements can move or traverse from one element to another.
Traversing form one element to another element is known as Iterating through the container.
While Iterating pointer can traverse forward only or may be backward also.
Iterator & their characteristics:
Iterator Access method Direction of movement I/O Capability Remark
1. Input Linear Forward only Read only Cannot be saved
2. Output Linear Forward only Write only Cannot be saved
3. Forward Linear Forward only Read/Write Can be saved
4. Bidirectional Linear Forward only Read/Write Can be saved
5. Random Random Forward & Backward Read/Write Can be saved
Only sequence associative containers are traversable with iterators.
Each type of iterator is used for performing specific functions.
Ra ndom acce ss
bidire ctiona l
forw ard
In put O utput
Ke y 2 V alue 2
Ke y N Value N
Practical List
A. Write Programs to Illustrate Simple C++ Concepts without Classes.
Q.1 Write C++ program to print sum and average of 3 numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c,sum;
float avg;
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
sum=a+b+c;
avg=sum/3.0;
cout<<”The sum of three numbers is”<<sum<<endl;
cout<<”The Average of three numbers is”<<avg;
getch();
}
Output:
Enter three numbers
10 18 02
The sum of three numbers is 30
The Average of three numbers is 10
Q.2 Write C++ program to print greatest of 3 numbers using nested if.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
if(a>b)
{
200 OOPs with C++ Programming
If(a>c)
{
Cout<<a<<”is greater”;
}
}
If(b>a)
{
If(b>c)
{
Cout<<b<<”is greater”;
}
}
If(c>a)
{
If(c>b)
{
Cout<<c<<”is greater”;
}
}
gecth();
}
Output:
Enter three numbers
10 18 02
18 is greater
Q.3 Write C++ program to print greatest of 3 numbers using logical operators.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<”Enter three numbers”<<endl;
cin>>a>>b>>c;
if(a>b && a>c)
{
Cout<<a<<”is greater”;
Practical List 201
}
elseif(b>a && b>c)
{
Cout<<b<<”is greater”;
}
else
{
Cout<<c<<”is greater”;
}
getch();
}
Output:
Enter three numbers
19 18 02
19 is greater
Q.4 Write C++ program to accept 3 subjects marks from user (Assuming of 100 marks paper)
calculate total, percentage & print grade accordingly.
Per Grade
75 and above Distinction
60 and 74 Ist class
50 and 59 IInd class
40 and 49 Pass class
Below 40 Fail
#include<iostream.h>
#include<conio.h>
void main()
{
int m1,m2,m3,tot;
float per;
clrscr();
cout<<”Enter three subjects marks”<<endl;
cin>>m1>>m2>>m3;
tot=m1+m2+m3;
per=tot/3.0;
if (per>=75)
cout<<”Distinction”;
else if (per>=60 && per<75)
cout<<”Ist class”;
else if ( per>=50 && per <=59)
202 OOPs with C++ Programming
cout<<”IIns class”;
else if ( per>=40 && per<=49)
cout<<”Pass class”;
else
cout<<”Fail”;
getch();
}
Output:
Enter three subjects marks
80 90 80
Distinction
Q.5 Write C++ program to print even numbers integers between 1 to 100
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,prime;
clrscr();
cout<<"The Even numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i+=2)
{
cout<<i<<" ";
}
Output:
The Even numbers from 1 to 100 are
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
Q.6 Write C++ program to print odd numbers integers between 1 to 100.
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,prime;
clrscr();
Practical List 203
break;
}
}
if(prime==1)
{
cout<<i<<" ";
}
}
getch();
}
Output:
The Prime numbers from 1 to 100 are
1 2 3 5 7 11 13 17 19
23 29 31 37 41 43 47 53 59
61 67 71 73 79 83 89 97
8
The factorial of a number is40320
Q.9 Write C++ program to print even numbers, odd numbers & prime integers between 1 to 100
in one program.
void main()
{
int i,j,prime;
clrscr();
cout<<"The Even numbers from 1 to 100 are"<<endl;
for(i=2;i<=100;i+=2)
{
cout<<i<<" ";
}
cout<<"\n\n"<<"The Odd numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i+=2)
{
cout<<i<<" ";
}
cout<<"\n\n"<<"The Prime numbers from 1 to 100 are"<<endl;
for(i=1;i<=100;i++)
{
prime=1;
for(j=2;j<=i-1;j++)
{
if(i%j==0)
{
prime=0;
break;
}
}
if(prime==1)
{
cout<<i<<" ";
}
}
getch();
}
206 OOPs with C++ Programming
Output:
The Even numbers from 1 to 100 are
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80
82 84 86 88 90 92 94 96 98 100
The Odd numbers from 1 to 100 are
1 3 5 7 9 11 13 15 17 19
21 23 25 27 29 31 33 35 37 39
41 43 45 47 49 51 53 55 57 59
61 63 65 67 69 71 73 75 77 79
81 83 85 87 89 91 93 95 97 99
The Prime numbers from 1 to 100 are
1 2 3 5 7 11 13 17 19 23
29 31 37 41 43 47 53 59 61 67
71 73 79 83 89 97
Q.10 Write C++ program to give example of switch case by accepting a character from the user.
/* Program : The switch statement */
#include <iostream.h>
void main()
{
char c ;
cout<<"Enter any one character from the word 'worry': ";
cin>>c;
switch (c)
{
case 'W':
case 'w':cout<<"I am in case w\n";
break ;
case 'O':
case 'o':cout<<"I am in case o\n";
break ;
case 'R':
case 'r':cout<<"I am in case r\n";
break ;
case 'Y':
case 'y':cout<<"I am in case y\n";
break ;
Practical List 207
Q.11 Write C++ program to give example of Airthmertic, Relational & Logical operations using
switch case by providing menu driven facility.
/* Program: The switch statement */
#include <iostream.h>
#include<conio.h>
void main()
{
int select , choice , x , y , i ;
clrscr();
cout<<"Enter any two integer values : ";
cin>>x>>y;
cout<<"1. Arithmetic\n";
cout<<"2. Relational\n";
cout<<"3. Logical\n";
switch (choice)
{
case 1 : cout<<"Addition of "<<x<<" and "<<y<<" : "<<x+y;
break ;
case 2 : cout<<"Subtraction of "<<x<<" and "<<y<<" : "<<x-y;
break ;
case 3 : cout<<"Division of "<<x<<" and "<<y<<" : "<<float(x)/float(y);
break ;
case 4 : cout<<"Multiplication of "<<x<<" and "<<y<<" : "<<x*y;
break ;
case 5 : cout<<"Modulus of "<<x<<" and "<<y<<" : "<<x%y;
break ;
default : cout<<"Wrong choice !!";
}
break ;
case 2 : cout<<"\tMenu-Relational opeations\n";
cout<<"1. Greater than\n";
cout<<"2. Less than\n";
cout<<"3. Equal to\n";
cout<<"4. Less than or equal to\n";
cout<<"5. Greater thn or equal to\n";
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1 :
cout<<"Result of x greater than y : "<<(x>y);
break ;
case 2 :
cout<<"Result of x less than y : "<<(x<y);
break ;
case 3 :
cout<<"Result of x equal to y : "<<(x==y);
break ;
case 4 :
cout<<"Result of x less than or equal to y : "<<(x<=y);
break ;
case 5 :
cout<<"Result of x greater than or equal to y : "<<(x>=y);
Practical List 209
break ;
}
break ;
case 3 : cout<<"\tMenu-Logical operations\n";
cout<<"1. Logical AND\n";
cout<<"2. Logical OR\n";
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1 :
cout<<"Result of x AND y : "<<(x&&y);
break ;
case 2 :
cout<<"Result of x OR y : "<<(x||y);
break ;
}
break ;
}
getch () ;
}
Output:
Enter any two integer values
42
1. Arithmetic
2. Relational
3. Logical
Enter your choice
1
Menu-Arithmatic operations
1. Addition
2. Subtraction
3. Division
4. Multiplication
5. Modulus
Enter your choice
cin>>choice
1
Addition of 4 and 2 : 6
210 OOPs with C++ Programming
cout<<j<<" ";
}
cout<<endl;
}
getch();
}
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
cout<<i<<" ";
}
cout<<endl;
}
getch();
}
clrscr();
cout<<"enter radius"<<endl;
cin>>r;
a1=area(r);
cout<<"The area is "<<a1;
getch();
}
float area(float r1)
{
float pi=3.1415,area;
area=pi*r1*r1;
return area;
}
Output:
Enter radius
5
The area is 78.53
Q.2 Write C++ program to print maximum of two numbers using function.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,m;
int max(int x ,int y);
clrscr();
cout<<"enter the value of a &b"<<endl;
cin>>a>>b;
m=max(a,b);
cout<<"the maximum no. is"<<m;
getch();
}
int max(int x, int y)
{
if(x>y)
{
return x;
}
Practical List 215
else
{
return y;
}
}
Output:
enter the value of a &b
58
the maximum no. is 8
Q.4 Write C++ program to print sum and average of three numbers using function.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
void sumavg(int x, int y, int z);
clrscr();
cout<<"enter 3 numbers"<<endl;
cin>>a>>b>>c;
sumavg(a,b,c);
getch();
}
void sumavg(int x, int y, int z)
{
int s;
float avg;
s = x+y+z;
avg=s/3.0;
cout<<"The sum of three numbers is "<<s<<endl;
cout<<"The average of three numbers is "<<avg<<endl;
}
enter 3 numbers
80 90 80
The sum of three numbers is 250
The average of three numbers is 83.333
Q.5 Write C++ program to swap two integers, two floats, two characters using function
overloading.
#include<iostream.h>
#include<conio.h>
void swap(int a,int b);
void swap(float a,float b);
void swap(char a,char b);
void main()
{
int x,y;
float fx,fy;
char cx,cy;
clrscr();
cout<<"enter x y"<<endl;
Practical List 217
cin>>x>>y;
cout<<"enter fx fy"<<endl;
cin>>fx>>fy;
cout<<"enter cx cy"<<endl;
cin>>cx>>cy;
swap(x,y);
swap(fx,fy);
swap(cx,cy);
getch();
}
void swap(int a, int b)
{
int temp;
temp=b;
b=a;
a=temp;
cout<<"the value of x is "<<a<<endl;
cout<<"the value of y is "<<b<<endl;
}
void swap(float a, float b)
{
float temp;
temp=b;
b=a;
a=temp;
cout<<"the value of fx is "<<a<<endl;
cout<<"the value of fy is "<<b<<endl;
}
void swap(char a, char b)
{
char temp;
temp=b;
b=a;
a=temp;
cout<<"the value of cx is "<<a<<endl;
cout<<"the value of cy is "<<b<<endl;
}
218 OOPs with C++ Programming
Q.6 Write C++ program to calculate area of circle, area of rectangle, area of right angle triangle
using function overloading
#include<iostream.h>
#include<conio.h>
float area(int r1);
float area(double b1,double h1);
int area(int l1, int b1);
void main()
{
int r,l,b2,a3;
double b,h,a1,a2;
clrscr();
cout<<"enter the radius"<<endl;
cin>>r;
cout<<"enter the breath & height"<<endl;
cin>>b>>h;
cout<<"enter the length & breath"<<endl;
cin>>l>>b2;
a1=area(r);
a2=area(b,h);
a3=area(l,b2);
cout<<"\n the area of circle is "<<a1;
cout<<"\n the area of triangle is "<<a2;
cout<<"\n the area of rectangle is "<<a3;
getch();
}
float area(int r1)
{
float a;
a = 3.1415*r1*r1;
return a;
}
float area(double b1, double h1)
{
float z;
z=0.5*b1*h1;
return z;
}
int area(int l1, int b1)
Practical List 219
{
int z;
z=l1*b1;
return z;
}
Q.7 Write C++ program to give demo pointer variable by displaying the address of variables and
incrementing the addresses of pointer variables.
#include<iostream.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
cout<<"value of i is "<<i<<endl;
cout<<"value of j is "<<j<<endl;
cout<<"value of k is "<<k<<endl;
x=&i;
y=&j;
z=&k;
cout<<"original value of x is "<<x<<endl;
cout<<"original value of y is "<<y<<endl;
cout<<"original value of z is "<<z<<endl;
cout<<"original value of x is "<<*x<<endl;
cout<<"original value of y is "<<*y<<endl;
cout<<"original value of z is "<<*z<<endl;
x--;
y--;
z--;
cout<<"new value of x is "<<x<<endl;
cout<<"new value of y is "<<y<<endl;
cout<<"new value of z is "<<z<<endl;
getch();
}
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
cout<<"value of i is "<<i<<endl;
cout<<"value of j is "<<j<<endl;
cout<<"value of k is "<<k<<endl;
x=&i;
y=&j;
z=&k;
cout<<"original value of x is "<<x<<endl;
cout<<"original value of y is "<<y<<endl;
cout<<"original value of z is "<<z<<endl;
x++;
y++;
z++;
cout<<"new value of x is "<<x<<endl;
cout<<"new value of y is "<<y<<endl;
cout<<"new value of z is "<<z<<endl;
getch();
}
Q.9 Write C++ program to print area & circumference of a circle using functions.
#include<iostream.h>
#include<conio.h>
void arear(int r,float *a,float *c);
void main()
{
int radius;
float area,circum;
cout<<"enter the radius"<<endl;
cin>>radius;
arear(radius,&area,&circum);
cout<<"area is"<<area<<endl;
cout<<"circumference is "<<circum<<endl;
getch();
}
void arear(int r,float *a,float *c)
Practical List 221
{
*a=3.14*r*r;
*c=2*3.14*r;
}
Q.11 Write C++ program to declare array elements & display array element through pointer.
#include<iostream.h>
#include<conio.h>
void main()
{
int b[]={10,20,30,40,50};
int i;
for(i=0;i<=4;i++)
{
cout<<*(b+i)<<endl;
}
getch();
}
222 OOPs with C++ Programming
Q.12 Write C++ program to combine two strings using function using pointers.
#include<iostream.h>
#include<conio.h>
#include<string.h>
char *combine(char *,char *);
void main()
{
char a[10],b[10],*p;
strcpy(a,"horse");
strcpy(b,"fly");
p=combine(a,b);
cout<<p;
getch();
}
char *combine(char *s,char *t)
{
int x,y;
char r[100];
strcpy(r,s);
y=strlen(r);
for(x=y;*t!='\0';x++)
{
r[x]=*t++;
}
r[x]='\0';
return r;
}
char cx,cy;
clrscr();
cout<<"enter x y"<<endl;
cin>>x>>y;
cout<<"enter fx fy"<<endl;
cin>>fx>>fy;
cout<<"enter cx cy"<<endl;
cin>>cx>>cy;
swap(x,y);
swap(fx,fy);
swap(cx,cy);
getch();
}
void swap(int a, int b)
{
int temp;
temp=b;
b=a;
a=temp;
cout<<"the value of x is "<<a<<endl;
cout<<"the value of y is "<<b<<endl;
}
void swap(float a, float b)
{
float temp;
temp=b;
b=a;
a=temp;
cout<<"the value of fx is "<<a<<endl;
cout<<"the value of fy is "<<b<<endl;
}
void swap(char a, char b)
{
char temp;
temp=b;
b=a;
a=temp;
cout<<"the value of cx is "<<a<<endl;
cout<<"the value of cy is "<<b<<endl;
}
224 OOPs with C++ Programming
Q.2 Write C++ program to print area of circle, area of rectangle, area of right angle triangle
using function overloading with class.
#include<iostream.h>
#include<conio.h>
float area(int r1);
float area(double b1,double h1);
int area(int l1, int b1);
void main()
{
int r,l,b2,a3;
double b,h,a1,a2;
clrscr();
cout<<"enter the radius"<<endl;
cin>>r;
cout<<"enter the breath & height"<<endl;
cin>>b>>h;
cout<<"enter the length & breath"<<endl;
cin>>l>>b2;
a1=area(r);
a2=area(b,h);
a3=area(l,b2);
cout<<"\n the area of circle is "<<a1;
cout<<"\n the area of triangle is "<<a2;
cout<<"\n the area of rectangle is "<<a3;
getch();
}
float area(int r1)
{
float a;
a = 3.1415*r1*r1;
return a;
}
float area(double b1, double h1)
{
float z;
z=0.5*b1*h1;
return z;
}
int area(int l1, int b1)
Practical List 225
{
int z;
z=l1*b1;
return z;
}
}
};
void main()
{
point p1,p2,p3,x1;
cout<<"\n\n";
[Link]();
[Link]();
[Link]();
[Link]();
[Link](p1,p2);
p3scalar(p1,p2);
getch();
}
Output:
Enter Point: 2 3
point=(2.3)
Enter Point: 5 4
point=(5.4)
Addition=(7,7)
Enter the value of scalar x: 6
Result 1=(12,18)
Result 2=(30,24)
Enter Point: 2 3
Q.2 Write C++ program to create a class bill, accept the number of units from the user through
get member function. The amount is calculated on the basic of following slabs:
Units Amount
First 100 60 Rs. Per Unit
Next 100 80 Rs. Per unit
Next 100 90 Rs. Per unit
Above 300 5000 Fix amount
#include<iostream.h>
#include<conio.h>
class bill
{
int unit;
float amt;
public:
void get()
Practical List 227
{
cout<<"enter the units used"<<endl;
cin>>unit;
}
void amount()
{
if(unit<=100)
{
amt=60*unit;
}
else if(unit>100 && unit<=200)
{
amt=60;
unit=unit-100;
amt=amt+(unit*80);
}
else if(unit>200 && unit<=300)
{
amt=60+80;
unit=unit-200;
amt=amt+(unit*90);
}
Else
{
Amt=5000;
}
}
void disp()
{
cout<<"ur amount is "<<amt<<endl<<endl;
}
};
void main()
{
bill b;
[Link]();
[Link]();
[Link]();
getch();
}
228 OOPs with C++ Programming
Q.3 Write a C++ program to create class called Rectangle data members as width, height,
member function to find area and Perimeter.
Source Code:
#include<iostream.h>
#include<conio.h>
class rectangle
{
private:
int h,w;
public:
void input()
{
cout<<"Enter the values of h and w";
cin>>h>>w;
}
void display()
{
cout<<"h-"<<h<<"\tw-"<<w;
}
void area()
{
int area;
area=h*w;
cout<<"\n Area Is:";
cout<<area<<"\n";
}
void peri()
{
int peri;
peri=2*(h+w);
cout<<"Perimeter Is:"<<peri;
}
};
void main()
{
rectangle r;
[Link]();
[Link]();
[Link]();
Practical List 229
[Link]();
getch();
}
Output:
Enter the values of h and w 5 40
h-5 w-40
Area Is:200
Perimeter Is:90
Q.5 Write a program to calculate mean value of two numbers with friend function by using
nesting member function.
#include<iostream.h>
#include<conio.h>
class fir
{
int x,y;
public:
void get()
{
cout<<"enter the value of x & y"<<endl;
cin>>x>>y;
}
friend float mean(fir f);
};
float mean(fir f)
{
return (f.x+f.y)/2;
}
void main()
{
fir f1;
clrscr();
[Link]();
cout<<"the mean value is "<<mean(f1);
getch();
}
Q. 6 Write a C++ program to create class cel, Accept temperature in Celsius through setc member
function. getc function is used to read the celsium temperature. Create class feh, Accept
temperature in Fahrenheit through setc member function. Getc function is used to read the
Fahrenheit temperature. Provide common friend function sum of both the classes to display the
sum of Celsius & Fahrenheit temperature.
#include<iostream.h>
#include<conio.h>
class feh;
class cel
{
float c;
public:
Practical List 231
void setc()
{
cout<<"Enter temp in Celsius ";
cin>>c;
}
float getc()
{
return c;
}
friend float sum(feh f,cel c);
};
class feh
{
float f;
public:
void setf()
{
cout<<"Enter temp in Feh ";
cin>>f;
}
float getf()
{
return f;
}
float display()
{
cout<<"Feh Temp is = "<<f<<endl;
return f;
}
friend float sum(feh f,cel c);
};
float sum(feh f,cel c)
{
return (f.f+c.c);
}
void main()
{
cel c1;
[Link]();
232 OOPs with C++ Programming
Q. 7 Write a C++ program to print maximum of the number from class first and class second
through common friend max of both the classes
#include<iostream.h>
#include<conio.h>
class sec;
class fir
{
int x;
public:
void get()
{
cout<<"enter the value of x"<<endl;
cin>>x;
}
void disp()
{
cout<<"the value of x "<<x<<endl;
}
friend void max(fir,sec)
};
class sec
{
int y;
public:
void get()
{
cout<<"enter the value of y "<<endl;
cin>>y;
}
void disp()
{
Practical List 233
{
cout<<"enter the value of x & y"<<endl;
cin>>x>>y;
}
void sum()
{
int z;
z=x+y;
cout<<"the sum is "<<z<<endl;
}
};
void main()
{
number s1,s2;
[Link]();
[Link]();
getch();
}
Q. 2 A bookshop maintains the inventory of books that are being sold at the shop. The list
includes details such as author, tilte, price,and publisher and stock position. Whenever a
coustomers wants a book, the sales person inputes the title and author and system searches the list
and display whether it is available or not. If it is not the appropriate message is desplayed. If it is
available then the system display the book details and request for the number of copies required.
If the number of copies are available the total cost off the requested copies is displayed; otherwise
error message is displayed. Design a system using a class called inventory with suitable member
functions and constructors.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class inventory
{
private :
char author[10],title[10],publisher[10];
int price,stock;
public :
inventory()
{
cout<<"enter title and author";
cin>>title>>author;
Practical List 235
char wish='y';
while(wish=='y')
{
cout<<"enter title and author of book for purchasing"<<endl;
cin>>t>>a;
for(i=0;i<3;i++)
{
n[i].search(t,a);
}
cout<<"do u want to purchase more";
cin>>wish;
}
getch();
}
public:
tcountry()
{
strcpy(name.s,'\0');
strcpy(capital.s,'\0');
population =0;
area=0;
strcpy(govt,'\0');
}
tcountry(char *n, char *c)
{
strcpy(name.s,n);
strcpy(capital.s,c);
population =50000;
area=45.56;
strcpy(govt,'\0');
}
tcountry(char *n, char *c,long double p, long double a=89.56, char g[10]="congress")
{
strcpy(name.s,n);
strcpy(capital.s,c);
population =p;
area=a;
strcpy(govt,g);
}
void display()
{
cout<<"the name is "<<name.s<<endl;
cout<<"the capital is "<<capital.s<<endl;
cout<<"population is "<<population<<endl;
cout<<"area is "<<area<<endl;
cout<<"govt is "<<govt<<endl;
}
};
void main()
{
tcountry t();
tcountry t1("hello","hi");
[Link]();
238 OOPs with C++ Programming
tcountry t2("india","delhi",100000);
[Link]();
getch();
}
Q. 4 Create a class student accept two numbers through parameterized constructor. Calculate
sum, subtraction, Multiplication, division through separate member function.
#include<iostream.h>
#include<conio.h>
class student
{
int x,y;
public :
student(int a, int b)
{
x=a;
y=b;
}
void sum()
{
int z=x+y;
cout<<"the sum is "<<z;
}
void sub()
{
int z=x-y;
cout<<"the sub is "<<z;
}
void mul()
{
int z=x*y;
cout<<"the multiplication is "<<z;
}
void div()
{
int z=x/y;
cout<<"the division is "<<z;
}
};
void main()
{
Practical List 239
student s(5,3);
[Link]();
[Link]();
[Link]();
[Link]();
getch();
}
Q. 5 Create a class student accept rollno, name & marks through parameterized constructor. And
display through display member function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[10];
float marks;
public:
student(int r, char n[10],float m)
{
rollno=r;
strcpy(name,n);
marks=m;
}
void disp()
{
cout<<"the rollno is"<<rollno<<endl;
cout<<"the name is "<<name<<endl;
cout<<"the marks is "<<marks;
}
};
void main()
{
student s=student(10,"chirag",98); // Explicit call of constructor
[Link]();
getch();
}
240 OOPs with C++ Programming
Q. 6 Create a class first accept one integer number through parameterized constructor, Overload
that constructor to accept two integers and calculate and print sum of two numbers, Overload
that constructor to accept three float numbers and calculate sum of three float numbers and print
sum.
#include<iostream.h>
#include<conio.h>
class first
{
private:
int x,ix,iy;
float fx,fy,fz;
public :
first(int x1)
{
x=x1;
cout<<"the value of x is "<<x<<endl;
}
first(int x1,int y1)
{
ix=x1;
iy=y1;
cout<<"the value of ix & iy is "<<ix<<" "<<iy<<endl;
int sum=ix+iy;
cout<<"the sum of ix & iy is "<<sum<<endl;
}
first(float fx1, float fy1, float fz1)
{
fx=fx1;
fy=fy1;
fz=fz1;
cout<<"the value of fx,fy & fz is "<<fx<<" "<<fy<<" "<<fz<<endl;
int sum1=fx+fy+fz;
cout<<"the sum of fx,fy & fz is :"<<sum1<<endl;
}
};
void main()
{
clrscr();
first f(8);
first f1(2,3);
first f2(6.0,7.2,8.3);
getch();
}
Practical List 241
Q. 7 Write a program in C++ to create class date1 having data members day, month and year,
default value year = 2002, display date for default, for another overwrite year value to the deafult
and display the date for second object.
#include<iostream.h>
#include<conio.h>
class date1
{
private:
int day,month,year;
public:
date1(int d,int m,int y=2002)
{
day=d;
month=m;
year=y;
}
void disp()
{
cout<<"the date is: "<<day<<"/"<<month<<"/"<<year<<endl;
}
};
void main()
{
date1 d(5,9);
[Link]();
date1 d1(8,11,2003);
[Link]();
getch();
}
Q. 8 Wirte a C++ program to create a class show assign a public variable value x through main
function. Display the value of x through disp function and provide a Destructor to display the
destructor message.
#include<iostream.h>
#include<conio.h>
class show
{
public:
int x;
void disp()
242 OOPs with C++ Programming
{
cout<<x<<endl;
}
~show()
{
cout<<"Destructor is called"<<endl;
}
};
void main()
{
a obj;
clrscr();
obj.x=10;
[Link]();
getch();
}
Q. 9 Create class bank having data members name, accno, type of account and balance. Accept
details through constructor, Provide a member functions (1) deposit amount, (2) withdraw
amount after checking bal (3) disp name & balance.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class bank
{
char name[15];
int accno;
char type[10];
float bal;
public :
bank(char n[15], int ac, char t[10],float b)
{
strcpy(name,n);
accno=ac;
strcpy(type,t);
bal=b;
}
void deposit()
{
Practical List 243
int y;
cout<<"enter the amount to deposit"<<endl;
cin>>y;
bal = bal +y;
}
void withdraw()
{
int y;
cout<<"enter the amount to withdraw"<<endl;
cin>>y;
if((bal-y)>500)
{
bal =bal-y;
}
else
{
cout<<"no balance available";
}
}
void display()
{
cout<<"the name is "<<name<<endl;
cout<<"the balance is "<<bal;
}
};
void main()
{
clrscr();
bank b("kiran",819,"saving",10000);
bank b1("chirag”,485,"current",50000);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
getch();
}
244 OOPs with C++ Programming
Q. 2 Write a C++ program to overload unary ++ operator using operator function as a member
function
#include<iostream.h>
#include<conio.h>
class abc
{
int x,y;
public:
abc(int a,int b)
{
x=a;
y=b;
}
void operator ++(void)
{
x=++x;
y=++y;
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
int x,y;
clrscr();
abc s(2,3);
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
++s;
[Link]();
getch();
}
Q.3 Write a C++ program to overload unary - operator using operator function as a friend
function
#include<iostream.h>
#include<conio.h>
class abc
246 OOPs with C++ Programming
{
int x,y;
public:
abc(int a,int b)
{
x=a;
y=b;
}
void friend operator ++(abc &s)
{
s.x=++s.x;
s.y=++s.y;
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
int x,y;
clrscr();
abc s(2,3);
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
++s;
[Link]();
getch();
}
Q. 4 Write a C++ program to overload binary - operator using operator function as a member
function
#include<iostream.h>
#include<conio.h>
class abc
{
int x,y;
public:
Practical List 247
abc()
{
}
abc(int a,int b)
{
x=a;
y=b;
}
abc operator +(abc &s)
{
abc s3;
s3.x=x+s.x;
s3.y=y+s.y;
return(s3);
}
void disp(void)
{
cout<<" x is "<<x<<endl;
cout<<" y is "<<y<<endl<<endl;
}
};
void main()
{
clrscr();
abc s1(2,3);
abc s2(4,5);
abc s3;
[Link]();
[Link]();
cout<<"after operator over-loading"<<endl<<endl;
s3=s1+s2;
[Link]();
getch();
}
Q. 5 Write a C++ program to overload unary >> & << operators by giving suitable example.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class bird
{
248 OOPs with C++ Programming
private :
char *name, *flying, *color;
int size;
public :
bird()
{
strcpy(name,'\0');
strcpy(flying,'\0');
strcpy(color,'\0');
size=0;
}
friend istream & operator >>(istream &din, bird &b);
friend ostream & operator <<(ostream &dout, bird &b);
};
istream & operator >>(istream &din, bird &b)
{
din>>[Link];
din>>[Link];
din>>[Link];
din>>[Link];
return din;
}
ostream & operator <<(ostream &dout, bird &b)
{
dout<<[Link]<<endl;
dout<<[Link]<<endl;
dout<<[Link]<<endl;
dout<<[Link]<<endl;
return dout;
}
void main()
{
bird b;
cout<<"enter the elements name,flying,color & size";
cin>>b;
cout<<"the elements are:"<<"\n";
cout<<b;
getch();
}
Practical List 249
Q. 6 Write a C++ program to overload unary ! operator so that it will return the length of the
string.
/* overload! operator so that it will return the length of the string
without pointers */
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
char n[10];
public :
string(char b[10])
{
strcpy(n,b);
}
void operator!(void)
{
cout<<"the length of entered string is "<<strlen(n);
}
};
void main()
{
clrscr();
char k[10];
cout<<"enter the string"<<endl;
cin>>k;
string n(k);
!n;
getch();
}
Q. 7 Write a C++ program to overload binary + operator using to combine two strings. /*
overload the + operator so that the two srings can be concatenated e.g. "Chirag "+"Gurbani"
="Chirag Gurbani" */
#include<iostream.h>
#include<conio.h>
#include<string.h>
class string
{
250 OOPs with C++ Programming
char *n;
char *n1;
public :
string()
{
}
string(char *b, char *b1)
{
n=b;
n1=b1;
}
void operator+(void)
{
cout<<"After adding the two strings are "<<strcat(n,n1);
}
};
void main()
{
clrscr();
char *k,*k1;
cout<<"enter the first string"<<endl;
cin>>k;
cout<<"enter the second string "<<endl;
cin>>k1;
string n(k,k1);
+n;
getch();
}
int x,y;
void setdata()
{
cout<<"\n Enter two numbers";
cin>>x>>y;
}
void display()
{
cout<<"x="<<x<<"y="<<y ;
}
int add()
{
return(x+y);
}
};
class cSubtract:public cAdd
{
public:
int sub()
{
return(x-y);
}
};
void main()
{
clrscr();
cAdd a;
[Link]();
int b=[Link]();
cout<<"Addition="<<b<<endl;
cSubtract p;
[Link]();
int c=[Link]();
cout<<"Subtraction="<<c<<endl;
getch();
}
Output:
Enter two numbers 4 54
Addition=58
252 OOPs with C++ Programming
Q.3 Write a program in C++ to create a class stud to read the rollno & print rollno through
member functions, create derived class art from stud base class to accept & display the arts
marks, same way create medi derived class & engg. derived class from stud base class to accept
and print the marks. In engg. provide a member functions for mechanical electrical & civil.
Provide a hierarchical inheritance to create a menu options from the user for selecting the
category.
#include<iostream.h>
#include<conio.h>
class stud
{
protected:
int roll;
public:
void getst()
{
cout<<"enter roll no"<<endl;
cin>>roll;
}
void dispst()
254 OOPs with C++ Programming
{
cout<<" ur roll no is "<<roll<<endl;
}
};
class art:public stud
{
protected:
int marks;
public:
void getart()
{
getst();
cout<<"enter ur marks"<<endl;
cin>>marks;
}
void dispart()
{
dispst();
cout<<"ur marks in arts are "<<marks<<endl;
}
};
class medi:public stud
{
protected:
int marks;
public:
void getmedi()
{
getst();
cout<<"enter ur marks"<<endl;
cin>>marks;
}
void dispmedi()
{
dispst();
cout<<"ur marks in medical are "<<marks<<endl;
}
};
class engg:public stud
Practical List 255
{
protected:
int marks;
public:
void mech()
{
getst();
cout<<"enter the marks of mechanical subj "<<endl;
cin>>marks;
}
void elec()
{
getst();
cout<<"enter the marks of electrical subj "<<endl;
cin>>marks;
}
void civil()
{
getst();
cout<<"enter the marks of civil subj "<<endl;
cin>>marks;
}
void dispengg()
{
dispst();
cout<<"the marks of subj are "<<marks<<endl;
}
};
void main()
{
engg e1;
art a1;
medi m1;
int ch;
clrscr();
[Link]();
[Link]();
[Link]();
[Link]();
256 OOPs with C++ Programming
[Link]();
[Link]();
cout<<" 1. mechanical"<<endl;
cout<<" 2. electrical"<<endl;
cout<<" 3. civil "<<endl<<endl;
cout<<"enter ur choice"<<endl;
cin>>ch;
switch(ch)
{
case 1:
[Link]();
break;
case2:
[Link]();
break;
case 3:
[Link]();
break;
default :
cout<<"enter correct number "<<endl;
break;
}
[Link]();
getch();
}
int sum;
cout<<"Enter a& b"<<endl;
cin>>a>>b;
sum=a+b;
cout<<"the sum is "<<sum;
}
};
class der1:public base
{
public:
int c;
void sum()
{
int sum;
cout<<"Enter a,b,c"<<endl;
cin>>a>>b>>c;
sum=a+b+c;
cout<<"the sum is "<<sum;
}
};
class der2:public der1
{
public:
int d;
void sum()
{
int sum;
cout<<"enter the a,b,c,d"<<endl;
cin>>a>>b>>c>>d;
sum=a+b+c+d;
cout<<"the sum is"<<sum;
}
};
void main()
{
clrscr();
base *p,s;
der1 d1;
der2 d2;
258 OOPs with C++ Programming
p=&s;
p->sum();
p= &d1;
p->sum();
p=&d2;
p->sum();
getch();
}
Q. 2 write a program to create class cPolygon having pure virtual function Area(). Derive two
classes from it called cRectangle and cTriangle to override Area().
Source Code:
#include<iostream.h>
#include<conio.h>
#include<math.h>
class cPolygon
{
public:
int l,b;
virtual void Area()=0;
virtual void display()=0;
};
class cRectangle:public cPolygon
{
int A,b;
public:
cRectangle(int l1,int b1)
{
l=l1;
b=b1;
}
void display()
{
cout<<"\n Length="<<l;
cout<<"\n Breadth="<<b;
}
void Area()
{
A=l*b;
Practical List 259
base=&t;
base->display();
cout<<"\n";
base->Area();
getch();
}
Output:
Length=2
Breadth=5
Area Of Rectangle=10
L=4
B=5
C=6
Area Of Triangle =6.480741
Q. 2 Example of C++ program with command line arguments of main function by passing array
& storing into a file.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main(int argc, char * argv[])
Practical List 261
{
int number[9]={11,22,44,33,55,66,77,88,99};
if(argc!=3)
{
cout<<"argc="<<argc<<"\n";
cout<<"error in argument";
exit(1);
}
ofstream fout1,fout2;
[Link](argv[1]);
if([Link]())
{
cout<<"could not open file"<<argv[1]<<"\n";
exit(1);
}
[Link](argv[2]);
if([Link]())
{
cout<<"could not open file"<<argv[2]<<"\n";
exit(1);
}
for(int i=0;i<9;i++)
{
if(number[i]%2==0)
{
fout2<<number[i]<<" ";
}
else
{
fout1<<number[i]<<" ";
}
}
[Link]();
[Link]();
ifstream fin;
char ch;
for(i=1;i<argc;i++)
{
[Link](argv[i]);
262 OOPs with C++ Programming
Q. 3 Example of C++ program accepting the details name, code and cost from user, store the
details in a file and reading the contents & displaying the details.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata();
void writedata();
};
void inventory :: readdata()
{
cout<<"enter name code cost"<<"\n";
cin>>name>>code>>cost;
}
void inventory:: writedata()
{
cout<<setw(10)<<name<<"\n";
cout<<setw(10)<<code<<"\n";
cout<<setw(10)<<setprecision(2)<<cost<<"\n";
}
void main()
{
Practical List 263
inventory item[3];
fstream file;
clrscr();
[Link]("[Link]",ios::in|ios::out);
cout<<"enter the details" <<"\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
[Link]((char *) &item[i],sizeof(item[i]));
}
[Link](0);
for(i=0;i<3;i++)
{
[Link]((char*) &item[i],sizeof(item[i]));
item[i].writedata();
}
[Link]();
getch();
}
Q. 4 Write a C++ program to read the contents of [Link] & [Link] file & display the
contents of country & capital by reading both the files.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
const n=80;
char line[80];
clrscr();
ifstream f1,f2;
[Link]("[Link]");
[Link]("[Link]");
for(int i=1;i<10;i++)
{
if([Link]()!=0)
{
cout<<"exit from country"<<endl;
exit(1);
264 OOPs with C++ Programming
}
[Link](line,n);
cout<<"country of"<<line;
if([Link]()!=0)
{
cout<<"exit from capital"<<endl;
exit(1);
}
[Link](line,n);
cout<<"capital of"<<line;
}
getch();
}
Q. 5 Write a C++ program to create [Link] file & store the names of the countries. Create
another file [Link] & store the names of capitals of the countries. Read the contents of both
the files & display on the output.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
const n=80;
char line[80];
clrscr();
ofstream out;
[Link]("[Link]");
out<<"united state of america"<<"\n";
out<<"united kingdom"<<"\n";
out<<"south korea";
[Link]();
[Link]("[Link]");
out<<"london"<<"\n";
out<<"paris"<<"\n";
out<<"delhi";
[Link]();
ifstream fin;
[Link]("[Link]");
while(fin)
{
[Link](line,n);
Practical List 265
cout<<line;
}
[Link]();
[Link]("[Link]");
while(fin)
{
[Link](line,n);
cout<<line;
}
[Link]();
getch();
}
Q. 6 Write a C++ program to create a file to store Cricketers name in it and then display them on
screen.
Source Code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
clrscr();
char name[80];
int i;
cout<<"\n Enter number of Cricketers";
cin>>i;
int n=0;
ofstream of("Cricketer");
do
{
cout<<"\n Enter Name:";
cin>>name;
of<<name<<"\n";
n++;
}while(n<i);
[Link]();
ifstream ifs("Cricketer");
cout<<"\n Data From file is:\n";
while(ifs)
{
266 OOPs with C++ Programming
[Link](name,80);
cout<<name;
}
[Link]();
getch();
}
Output:
Enter number of Cricketers 4
Enter Name: Sachin
Enter Name: Saurabh
Enter Name: Piyush
Enter Name: Dhoni
Data From file is:
SachinSaurabhPiyushDhoni
cout<<a<<" is Minimum";
}
};
void main()
{
clrscr();
number<int>x;
[Link](2,3);
[Link]();
[Link]();
number<float>y;
[Link](10.0,20.5);
[Link]();
[Link]();
getch();
}
Output:
a=2
b=3
2 is Minimum
a=10
b=20.5
10 is Minimum
throw b;
cout<<"c="<<a/b;
}
catch(double b)
{
cout<<"\n As Division By Zero Occured";
}
getch();
}
Output:
(a) Enter Two Numbers: 4 0
As Division By Zero Occurred
(b) Enter Two Numbers: 12 4
c=3
clrscr();
[Link]('<');
[Link](3);
for(int n=1;n<=6;n++)
{
[Link](5);
cout<<n;
[Link](10);
cout<<1.0/float(n)<<endl;
if(n==3)
{
[Link]('>');
}
}
cout<<"padding changed ";
[Link]('#');
[Link](15);
cout<<12.345678<<"\n";
getch();
}
[Link](8);
cout<<cost[i];
int value=item[i] * cost[i];
[Link](15);
cout<<value<<"\n";
sum=sum+value;
}
cout<<"grand total is ";
[Link](2);
cout<<sum;
getch();
}
Model Question Paper
Note: (1) All questions are compulsory.
(2) Figures to the right indicate marks.
(3) Write suitable programs wherever necessary.
Q. 1 Answer the following (Attempt any 3) (15)
(a) Explain object oriented concept with data encapsulation and data inheritance
by explaining features of C++ language.
(b) Explain how data polymorphism can be achieved by function overloading and
operator overloading by giving suitable example.
(c) Explain how file handling is provided in C++ language and what are different
classes for file stream operations.
(d) Explain difference between Cin and Cout objects with example, also explain #
include directives used in C++.
Q. 2 Answer the following (Attempt any 3) (15)
(a) Explain what is Class, how to define data members and member functions with
the different scope of variables. Draw a Class diagram to represent it by giving
suitable example.
(b) Explain how objects can be created and destroyed with example, also explain
with example how parameterised constructor can be called.
(c) Explain what do you mean by function declaration with prototype statement,
function call and function definition. How it can be achieved using default
arguments?
(d) Explain how non member function can access the properties and methods of
the class. How you can achieve this. What are the rules followed to achieve
this?
Q. 3 Answer the following (Attempt any 3) (15)
(a) Explain inheritance with reusability concept and state types of inheritance.
Give suitable example of multilevel inheritance by creating a base class
student having data members Rollno, name. Inherit student base class create
derived class Sem1 to accept Semester 1 Marks from the user. Created derived
class Sem2 to accept Semester 2 marks. Create derived class result to display
total marks of Sem1 and Sem2 along with Rollno and Name and Percentage of
the student.
(b) Explain what is the use of virtual function, what is difference between virtual
function and pure virtual function.
272 OOPs with C++ Programming
(c) Explain C++ streams and manipulator used for managing output with suitable
example.
(d) Explain how pointer to object and pointer to derived class can be achieved with
suitable example.
Q. 4 Explain the following (Attempt any 3) (15)
(a) Explain open() and Close() methods of files, how to detect end of file. Write a
program to create a file. Store the data and display contents of a file.
(b) Explain function templates with multiple parameters.
(c) Explain use of Exception handling with try, catch and throw block. Give
suitable example how re-throwing of an Exception is provided.
(d) Explain what is STL and what are components of STL.
ISBN: 978-93-5433-335-4