Oops
Oops
MCA101
OBJECT ORIENTED
PROGRAMMING
F.Y. MCA (CBCS)
SEMESTER - I
© UNIVERSITY OF MUMBAI
Course Co-ordinator
Asst. Prof. Reshma Kurkute
Department - MCA, University of Mumbai, IDOL
Asst. Prof. Shardul Gavande
Department - MCA, University of Mumbai, IDOL
Course Writer
Asst. Prof. Nikhil Pawnikar
Department - UDIT, University of Mumbai, IDOL
Asst. Prof. Dhanraj Jadhav
Department - UDIT, University of Mumbai, IDOL
Asst. Prof. Seema Vishwakarma
Vidyalankar School of Information Technology, Wadala East, Mumbai.
Asst. Prof. Madhavi Auoralkar
Vidyalankar School of Information Technology, Wadala East, Mumbai.
Asst. Prof. Milind Thorat
K. J. Somaiya Institute of Engineering & I.T., Sion. Mumbai.
Published by
Dr. Prakash Mahanwar, Director Incharge
on behalf of Institute of Distance & Open Learning,University of Mumbai, Mumbai
and Printed at Printers Name
Printers address
ii
CONTENTS
1. Programming Basics.................................................................................. 01
2. Introduction to C++................................................................................... 38
4. Operator Overloading................................................................................ 77
8. Streams.................................................................................................... 175
iii
Object Oriented Programming
F.Y. MCA (CBCS)
Semester - I
SYLLABUS
iv
Sr. Module Detailed Contents Hours
No.
v
vi
UNIT 1
1
PROGRAMMING BASICS
Unit Structure
1.1 Objectives
1.2 Introduction to Programming
1.3 Programming Paradigms
1.4 Programming Languages and Types
1.5 Introduction to C
1.5.1 Basic Program Structure
1.5.2 Execution flow of C Program
1.5.3 Directives
1.5.4 Basic Input /Output
1.6 Introduction to Object-Oriented Programming
1.6.1 OOP concepts
1.6.2 Advantages
1.6.3 Applications
1.6.4 Comparison of C and C++
1.6.5 Data Types
1.6.6 Control Structures
1.6.7 Operators and Expressions
1.7 Summary
1.8 Reference for further reading
1.9 Unit End Exercises
1
OBJECT ORIENTED PROGRAMMING
1.1 Objectives
1. syntax and
2. semantics
2
Chapter 1: Programming Basics
this paradigm is on how to achieve the goal? The paradigm consists of several
statements and after execution, the result is stored.
Advantage:
1. Very simple to implement
2. It contains loops, variables, etc.
Disadvantage:
1. A complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible
Advantages:
● Data security
● Inheritance
● Code reusability
● Flexible and abstraction is also present
3
OBJECT ORIENTED PROGRAMMING
4
Chapter 1: Programming Basics
5
OBJECT ORIENTED PROGRAMMING
1.5 Introduction to C
Example:
int main()
Main() function
{
return 0;
Return
}
6
Chapter 1: Programming Basics
2. Expanded source code is sent to the compiler which compiles the code and
converts it into assembly code.
3. The assembly code is sent to the assembler which assembles the code and
converts it into object code.
4. The object code is converted into executable code with the help of linker
which links it to the library such as header files.
5. The executable code is sent to the loader which loads it into memory and then
it is executed. After execution, output is sent to the console.
7
OBJECT ORIENTED PROGRAMMING
1.5.3 Directives
directive specifies how a compiler should process its input.
Directive Function
1. #include <stdio.h>
2. int main()
3. {
4. printf("C Programming");
5. return 0;
6. }
b. In C, scanf() is one of the commonly used functions to take input from the
user. The scanf() function reads formatted input from the standard input
such as keyboards.
8
Chapter 1: Programming Basics
Example:
1. #include <stdio.h>
2. int main()
3. {
4. int testInt;
5. printf("Enter an integer: ");
6. scanf("%d", &testInt);
7. printf("Number = %d",testInt);
8. return 0;
9. }
In OOPs, the Decomposition of a problem into several smaller units (entities) called
objects and then builds data and functions around these objects. Before Object-
Oriented Programming came, programs were written in a procedural language, they
were nothing but a long list of instructions. On the other hand, these objects can
interact with each other; this makes it easier to develop programs in OOP as we can
understand the relationship between them.
9
OBJECT ORIENTED PROGRAMMING
A class is like a blueprint of a data member and functions and objects are an
instance of the class. For example, let's say we have a class Car that has data
members (variables) such as speed, weight, price, and functions such as
gearChange(), slowDown(), brake(), etc. Now let's say I create an object of this
class named FordCar which uses these data members and functions and gives them
its values. Similarly, we can create as many objects.
Example:
class Car
{
//Data members
char name[20];
int speed;
int weight;
public:
//Functions
void brake(){
}
void slowDown(){
}
};
10
Chapter 1: Programming Basics
int main()
{
//ford is an object
Car ford;
}
Abstraction
Abstraction is a process of hiding background details from the user. For example,
When you send an SMS you just type the message, select the contact and click
send, the phone shows you that the message has been sent, what happens in the
background, when you click send button is hidden from you as it is not relevant to
you. Since classes use the concept of data abstraction, are known as Abstract Data
Type (ADT).
Encapsulation
The process of combining data and function into a single unit is known as
Encapsulation. This will not allow access to private data members from outside the
class. To achieve encapsulation, we make all data members of class private and
create public functions, using them we can get the values from these data members
or set the value to these data members.
Inheritance
Objects of one class obtain the properties of objects of another class. in other words,
accessing the property of parents (base) class from child class (derived).
Example:
#include <iostream>
using namespace std;
class ParentClass {
//data member
public:
int varone =100;
11
OBJECT ORIENTED PROGRAMMING
};
class ChildClass: public ParentClass {
public:
int vartwo = 500;
};
int main(void) {
ChildClass obj;
}
Polymorphism
Example:
#include <iostream>
using namespace std;
class Sum {
public:
int add(int num1,int num2){
return num1 + num2;
}
int add(int num1, int num2, int num3){
return num1 + num2 + num3;
}
};
int main(void) {
//Object of class Sum
Sum obj;
12
Chapter 1: Programming Basics
1.6.2 Advantages
a. Simplicity: the complexity is reduced and the simple program structure.
b. Modularity: each object forms a separate entity in oops.
c. Modifiability: Easy to make minor changes in the data representation.
modification inside a class do not affect any other part of a program since the
only public interface that the external world has to a class is through the use
of methods
d. Extensibility: adding new features or introducing a few new objects and
modifying some existing ones
e. Maintainability: objects can be maintained separately, making locating and
fixing of problems become easier
f. Re-usability: objects can be reused in different programs
1.6.3 Applications
1. Client-Server Systems
13
OBJECT ORIENTED PROGRAMMING
3. Object-Oriented Databases
Object Database Management Systems databases store objects instead of data, such
as real numbers and integers. Objects consist of the following:
Attributes: Attributes are data that define the traits of an object. This data can be
as simple as integers and real numbers. It can also be an allusion to a complex
object.
Methods: methods define the behavior and are also called functions or procedures.
Real-time systems have inherent complexities that make it difficult to build them.
These Object-Oriented techniques make it easier to handle those complexities.
These techniques use an integrated framework for presenting ways of dealing with
these complexities by providing an that includes schedulability analysis and
behavioral specifications.
In OOPs, Hypertext is similar to the regular text as it can be stored, searched, and
edited easily. The only difference is that hypertext is text with pointers to other text
as well.
14
Chapter 1: Programming Basics
This system includes formal as well as informal electronic systems, concerned with
information sharing and communication to and from people inside as well as
outside the organization. Some examples are:
Word processing
Web calendars
Desktop publishing
9. CIM/CAD/CAM Systems
OOP can also be used in manufacturing and design applications as it allows people
to reduce the try involved. For occasion, it can be used while designing blueprints,
flowcharts, etc. It is possible for the designers and engineers to produce these
flowcharts and blueprints accurately with help of OOPs..
These are computer applications which are developed to solve complex problems
about a specific domain, which is at a level far beyond the reach of a human brain.
C C++
15
OBJECT ORIENTED PROGRAMMING
Data and functions are separated in C Data and functions are encapsulated
because it is a procedural programming together in the form of an object in
language. C++.
Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.
16
Chapter 1: Programming Basics
scanf() and printf() functions are used for cin and cout are used for input/output
input/output in C. in C++.
1. Primitive Data Types: These data types are built-in types or predefined
data types and can be used by the user to declare variables.
Example: int, char, float, bool, etc. Primitive data types available in C++ are:
o Integer
o Character
o Boolean
o Floating Point
o Double Floating Point
o Valueless or Void
o Wide Character
17
OBJECT ORIENTED PROGRAMMING
2. Derived Data Types: These data-types derived from the primitive or built-
in datatypes are referred to as Derived Data Types. These can be of four types
namely:
o Function
o Array
o Pointer
o Reference
3. Abstract or User-Defined Data Types: These data types are defined by the
user itself. which is the same as defining a class in C++ or a structure. C++
provides the following user-defined datatypes:
o Class
o Structure
o Union
o Enumeration
o Typedef defined DataType
● Integer: The keyword used for integer data types is int. Integers typically
require 4 bytes of memory space and range from -2147483648 to
2147483647.
● Character: This data type is used for storing characters. The keyword used
for the character data type is char. Characters typically require 1 byte of
memory space and range from -128 to 127 or 0 to 255.
● Boolean: This data type is used for storing boolean values. A boolean
variable can store value either true or false. The keyword used for the boolean
data type is bool.
● Floating Point: This data type holds a real number and used for storing
single-precision floating-point values. The keyword used for the floating-
point data type is float. Float variables typically require 4 bytes of memory
space.
● Double Floating Point: this data type is used for storing decimal values. The
keyword used for the double floating-point data type is double. Double
variables require 8 bytes of memory space.
18
Chapter 1: Programming Basics
● void: Void means without any value. void data type represents a valueless
entity. The void data type is used for those functions which do not return a
value.
As the name implies, data type modifiers are used with built-in data types to modify
the length of data that a particular data type can hold.
Modifiers in C++
Long-Prefix Short-Prefix
Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:
Size
Data Type (in bytes) Range
short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to 2,147,483,647
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
long long int 8 -(2^63) to (2^63)-1
unsigned long long int 8 0 to 18,446,744,073,709,551,615
signed char 1 -128 to 127
unsigned char 1 0 to 255
float 4
19
OBJECT ORIENTED PROGRAMMING
Size
Data Type (in bytes) Range
double 8
long double 12
wchar_t 2 or 4 1 wide character
Note: Above values may vary from compiler to compiler. In the above example,
we have considered GCC 64 bit.
20
Chapter 1: Programming Basics
1. Sequence structure
The sequence structure is built into C++. In C++ statements are executed one
after the other in the order in which they are written that is, in sequence. For
example, a typical sequence structure in which two calculations are
performed in order.
Total=Total+grade; //add a grade to total
Counter=Counter+1; // add a 1 to counter
2. Selection structure:
This structure used for decisions, branching choosing between 2 or more
alternative paths. In C++, following are the types of selection statements:
● if
● if/else
● switch
Syntax:
if (condition) statement
where the condition is the expression that is being evaluated. If this condition is
true, the statement is executed. If it is false, the statement is ignored (not
executed) and the program continues on the next instruction after the conditional
structure.
For example, the following code fragment prints out x is 200 only if the value
stored in variable x is indeed 200:
Example:
if (x == 20)
cout << "x is 20";
If we want more than a single instruction to be executed in case that condition
is true we can specify a block of instructions using curly brackets { }:
21
OBJECT ORIENTED PROGRAMMING
if (x == 20)
{
cout << "x is ";
cout << x;
}
We can additionally specify what we want that happens if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with it is:
Syntax:
Example:
if (x == 98)
else
prints out on the screen x are 99 if indeed x is worth 99, but if it is not -and only if
not- it prints out x is not 100. The if + else structures can be concatenated to verify
a range of values. The following example shows its use telling if the present value
stored in x is positive, negative or none of the previous, that is to say, equal to zero.
Example
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
22
Chapter 1: Programming Basics
switch:
The syntax of the switch instruction is a bit peculiar. Its objective is to check several
possible constant values for expression, something similar to what we did at the
beginning of this section with the linking of several if and else if sentences. Its form
is the following:
Syntax:
switch (expression) {
case constant1:
block of instructions 1
break;
case constant2:
block of instructions 2
break;
.
.
.
default:
default block of instructions
}
Example:
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
23
OBJECT ORIENTED PROGRAMMING
For example, we are going to build a program to count down using a while loop:
Example:
// custom countdown using while
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FINISH!";
return 0;
}
The do-while loop.
Format:
24
Chapter 1: Programming Basics
Its functionality is the same as the while loop except for that condition in the do-
while is evaluated after the execution of statement instead of before, granting at
least one execution of statement even if the condition is never fulfilled. For
example, the following program echoes any number you enter until you enter 0.
Example:
// number echoer
#include <iostream.h>
int main ()
unsigned long n;
do {
cin >> n;
} while (n != 0);
return 0;
and its main function is to repeat statements while the condition remains true, like
the while loop. But also, to provide places to specify initialization instruction and
an increase in instruction. So this loop is specially designed to perform a repetitive
action with a counter.
25
OBJECT ORIENTED PROGRAMMING
2, the condition is checked, if it is true the loop continues, otherwise the loop
finishes, and the statement is skipped.
4, finally, whatever is specified in the increased field is executed and the loop gets
back to step 2.
Example:
26
Chapter 1: Programming Basics
Arithmetic Operators
27
OBJECT ORIENTED PROGRAMMING
Example:
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "1 - Value of c is :" << c << endl ;
c = a - b;
cout << "2 - Value of c is :" << c << endl
;
c = a * b;
cout << "3 - Value of c is :" << c << endl ;
c = a / b;
cout << "4 - Value of c is :" << c << endl ;
c = a % b;
cout << "5 - Value of c is :" << c << endl ;
c = a++;
cout << "6 - Value of c is :" << c << endl ;
c = a--;
cout << “7 - Value of c is :" << c << endl ;
return 0;
}
Output:
1 - Value of c is :31
2 - Value of c is :11
3 - Value of c is :210
3 - Value of c is :210
4 - Value of c is :2
5 - Value of c is :1
28
Chapter 1: Programming Basics
Relational Operators
29
OBJECT ORIENTED PROGRAMMING
Example:
#include <iostream>
using namespace std;
main()
{
int a = 25;
int b = 78;
int c ;
c = a + b;
cout << "1 - Value of c is :" << c << endl ;
c = a - b;
cout << "2 - Value of c is :" << c << endl ;
c = a * b;
cout << "3 - Value of c is :" << c << endl ;
c = a / b;
cout << "4 - Value of c is :" << c << endl ;
c = a % b;
cout << "5 - Value of c is :" << c << endl ;
return 0;
}
Output:
1 - Value of c is :103
2 - Value of c is :-53
3 - Value of c is :1950
4 - Value of c is :0
5 - Value of c is :25
30
Chapter 1: Programming Basics
Logical Operators
Example:
#include <iostream>
using namespace std;
main()
{
int a = 50;
int b = 2;
int c ;
if(a && b)
31
OBJECT ORIENTED PROGRAMMING
{
cout << "1 - Condition is true"<< endl ;
}
if(a || b)
{
cout << "2 - Condition is true"<< endl ;
}
/* After changing the values of a and b variable */
a = 4;
b = 60;
if(a && b)
{
cout << "3 - Condition is true"<< endl ;
} else
{
cout << "4 - Condition is not true"<< endl ;
}
if(!(a && b))
{
cout << "5 - Condition is true"<< endl ;
}
return 0;
}
Output:
1 - Condition is true
2 - Condition is true
3 - Condition is true
32
Chapter 1: Programming Basics
Bitwise Operators
Bitwise operator works on bits and performs a bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
<< Binary Left Shift Operator. The A << 2 will give 240 which is
left operand's value is moved 1111 0000
left by the number of bits
specified by the right operand.
>> Binary Right Shift Operator. A >> 2 will give 15 which is 0000
The left operand's value is 1111
moved right by the number of
bits specified by the right
operand.
33
OBJECT ORIENTED PROGRAMMING
Example:
#include <iostream>
using namespace std;
main()
{
unsigned int a = 98;
unsigned int b = 28;
int c = 0;
c = a & b;
cout << "1 - Value of c is : " << c << endl ;
c = a | b;
cout << "2 - Value of c is: " << c << endl ;
c = a ^ b;
cout << "3 - Value of c is: " << c << endl ;
c = ~a;
cout << "4 - Value of c is: " << c << endl ;
c = a << 2;
cout << "5 - Value of c is: " << c << endl ;
c = a >> 2;
cout << "6 - Value of c is: " << c << endl ;
return 0;
}
Output:
1 - Value of c is : 0
2 - Value of c is: 127
3 - Value of c is: 127
4 - Value of c is: -99
5 - Value of c is: 392
6 - Value of c is: 24
34
Chapter 1: Programming Basics
Assignment Operators
35
OBJECT ORIENTED PROGRAMMING
Example:
#include <iostream>
using namespace std;
int main()
{
// using "=" operator
int a = 10;
cout << "Value of a is "<<a<<"\n"; // using "+=" operator
a += 10;
cout << "Value of a is "<<a<<"\n"; // using "-=" operator
a -= 10;
cout << "Value of a is "<<a<<"\n"; // using "*=" operator
a *= 10;
cout << "Value of a is "<<a<<"\n"; // using "/=" operator
a /= 10;
cout << "Value of a is "<<a<<"\n";
return 0;
}
output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
36
Chapter 1: Programming Basics
1.7 Summary
● C++ is a superset of the C language.
● C++ adds a number of object-oriented features.
● C++ supports interactive input & output features.
● Object-Oriented Programming was invented to overcome the drawback of
the Procedural Oriented programming.
● C++ provides various types of tokens that include keywords, identifiers,
constants, string, and pointers.
● C++ provides various applications which is use in real life problems.
Reference Books:
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-
Hill
2. The C++ Programming Language, 4th Edition,Bjarne Stroustrup, Addison
Wesley
Web References:
1. www.geeksforgeeks.org
2. www.javatpoint.com
37
UNIT 2
2
INTRODUCTION TO C++
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Structure of a C++ Program
2.3 Execution Flow
2.4 Classes & Objects
2.5 Member functions
2.6 Access modifiers
2.7 Inline Functions
2.8 Passing parameters to a Function
2.8.1 Pass by value
2.8.2 Pass by reference
2.9 Function with default arguments
2.10 Function Overloading
2.11 Object as a Parameter
2.12 Static data members & Functions
2.13 Let us sum up
2.14 List of references
2.15 Bibliography
2.16 Unit end exercise
2.0 Objectives
After the completion of this unit, you will be able to understand following things,
1. Structure of C++ program & flow of the program.
2. Classes & objects, access modifiers, data members, member functions
3. Passing parameters to a function in different forms
4. Function overloading
38
Chapter 2: Introduction to C++
2.1 Introduction
As a programmer, it is very important to know the structure & flow of the program.
In this unit, we are going to learn about the structure, classes, objects, member
functions, data members, access modifiers. In the end, learner will be able to create
a class, can declare data members, member functions, can update the accessibility
using access modifiers, can access data from the class using objects.
Let us look at the very basic C++ Program. The name of the program is “Demo” so
its source file is “Demo.CPP”. It simply displays a sentence on the screen.
#include<iostream.h>
Using namespace std;
int main()
{
cout<<”Welcome to the world of C++\n”;
return(0);
}
39
OBJECT ORIENTED PROGRAMMING
7. Opening & closing braces of a C++ program signifies start & the end of the
function body respectively.
8. The function body can contain multiple statements. Program statement is a
fundamental unit of C++ program. Each statement ends with a semicolon (;).
9. “Cout” is called an identifier which corresponds to standard output stream.
The operator “<<” is called the insertion or put to operator.
When we run a program or execute a program, execution always starts from the
function called main(). If there is no main() function in your program, you will get
an error as the compiler will not understand where to start the execution. The main()
function calls member functions in various objects to carry out the program’s real
work. It also contains calls to other standalone functions.
There are various categories of objects that forms the basis for Object Oriented
Programming. Following are some categories of objects.
40
Chapter 2: Introduction to C++
1. Physical objects
a. Automobiles in a traffic-flow simulation
b. Electrical components in a circuit-design program
c. Countries in an economics model
d. Aircraft in an air traffic control system
3. Data-storage constructs
a. Customized arrays
b. Stacks
c. Linked lists
d. Binary trees
4. Human entities
a. Employees
b. Students
c. Customers
d. Salespeople
5. Collections of data
a. An inventory
b. A personnel file
c. A dictionary
d. A table of the latitudes and longitudes of world cities
41
OBJECT ORIENTED PROGRAMMING
The match between programming objects and real world objects is the result of
combining data and functions.
42
Chapter 2: Introduction to C++
s2.showdata();
return 0;
}
Program #1
In the above program Class Demo is being created. The Class Demo has one data
item and two member functions. We can access the data item inside the Demo class
using the available member functions. The first member function sets the value for
the data item and the other member function displays the value of the data item.
Placing data & and its functions together into a single entity is a central idea of
Object Oriented Programming. So we can show it diagrammatically as follows,
Class
A class is thus a description of a number of similar objects. This fits our non-
technical understandingof the word class. Mango. apple and banana are members
of the Fruit_basket class. There is no one fruit called “Fruit,” but specific fruits
with specific names are members of this class if they possess certain characteristics.
An object is often called an “instance” of a class.
Defining Objects:
Object is called as an instance of a class. Let’s check the output of the above
program. We have observed that two objects named s1 & s2 are used to access the
class. Each of the two objects is given a value, and each displays its value. Here’s
the output:
43
OBJECT ORIENTED PROGRAMMING
In the above program, inside main() function, we see two objects s1, s2. The
statement
means objects of type “Demo” have been created. The same process is also called
as instantiating. The above statement also states that the structure of object. It only
describes how they will look when they are created, just as a structure definition
describes how a structure will look but doesn’t create any structure variables. It is
objects that participate in program operations.
Defining a class:
class demo2 //define a class
{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data
{ somedata = d; }
void showdata() //member function to display data
{ cout << “\nData is “ << somedata; }
};
Program #2
The definition starts with the keyword CLASS, followed by the class name. Like a
structure, the body of the class is delimited by braces and terminated by a
semicolon. The above example of a class also shows keywords, Private & public.
This is a feature of Object Oriented programming called as ‘data hiding’.
Class data:
The above class demo2 contains one data item with ‘int’ datatype. The data item is
also called as data members. There can be any number of data items in a class. We
can also set the visibility of the data members as private or public.
44
Chapter 2: Introduction to C++
Member functions are functions that are included within a class. These are the
functions which are included within the class. Setdata() & showdata() are the
member functions used in class demo2. The function bodies of these functions have
been written on the same line as the braces that delimit them. You could also use
the more traditional format for these function definitions:
The member functions in the Demo2 class perform operations that are quite
common in classes: setting and retrieving the data stored in the class. The
setdata() function accepts a value as a parameter and sets the somedata variable
to this value. The showdata() function displays the value stored in somedata.
Member functions defined inside a class this way are created as inline functions
by default.
In the above Program #1, the below statements from main() function calls function
setdata().
s1.setdata(10);
s2.setdata(15);
These statements don’t look like normal function calls because the object names s1
and s2 connected to the function names. This strange syntax is used to call a
member function that is associated with a specific object. Because setdata() is a
member function of the Demo 1 class, it must always be called in connection with
an object of this class.
45
OBJECT ORIENTED PROGRAMMING
A member function is always called to act on a specific object, not on the class in
general.
Member functions of a class can be accessed only by an object of that class. To use
a member function, the dot operator (the period) connects the object name and the
member function. The syntax is similar to the way we refer to structure members,
but the parentheses signal that we’re executing a member function rather than
referring to a data item. The dot operator is also called the class member access
operator.
A key feature of object-oriented programming is data hiding. This term does not
refer to the activities of particularly paranoid programmers; rather it means that
data is concealed within a class so that it cannot be accessed mistakenly by
functions outside the class.
The primary mechanism for hiding data is to put it in a class and make it private.
Private data or functions can only be accessed from within the class. The primary
mechanism of hiding data is to make the function ‘private’. Private data or
functions can be accessed only inside the same class. On the other hand, public data
and member functions can be accessed from anywhere.
46
Chapter 2: Introduction to C++
Long sections of repeated code are generally better off as normal functions: The
savings in memory space is worth the comparatively small sacrifice in execution
speed. But making a short section of code into an ordinary function may result in
little savings in memory space, while imposing just as much time penalty as a larger
function.
In fact, if a function is very short, the instructions necessary to call it may take up
as much space as the instructions within the function body, so that there is not only
a time penalty but a space penalty as well. In such cases you could simply repeat
the necessary code in your program, inserting the same group of statements
wherever it was needed. The trouble with repeatedly inserting the same code is that
you lose the benefits of program organization and clarity that come with using
functions. The program may run faster and take less space, but the listing is longer
and more complex.
47
OBJECT ORIENTED PROGRAMMING
For Example:
//Inliner example
#include <iostream>
using namespace std;
// converts kilograms to grams
inline float kg2gm (int kilo)
{
return 1000 * kilo;
}
//--------------------------------------------------------------
int main()
{
float kg;
cout << “\nEnter kilograms: “;
cin >> kg;
48
Chapter 2: Introduction to C++
In the above program, we declared and defined function kg2gm using the keyword
inline. Later in the main(), we have called the inline function and calculated
Kilograms to grams.
Just like passing constants to functions, the function gives these new variables the
names and data types of the parameters specified in the declarator: ch of type char
and n of type int. It initializes these parameters to the values passed. They are then
accessed like other variables by statements in the function body. Passing arguments
in this way, where the function creates copies of the arguments passed to it, is called
passing by value.
In call by value, the actual value that is passed as argument is not changed after
performing some operation on it. When call by value is used, it creates a copy of
that variable into the stack section in memory. When the value is changed, it
changes the value of that copy, the actual value remains the same.
Example:
#include<iostream>
void my_fun(int x)
{
x = 50;
cout<< "Value of x from my_fun: " << x << endl;
}
main()
{
int x = 10;
my_fun(x);
cout << "Value of x from main function: " << x;
49
OBJECT ORIENTED PROGRAMMING
}
Output:
Value of x from my_fun: 50
Value of x from main function: 10
In call by reference the actual value that is passed as argument is changed after
performing some operation on it. When call by reference is used, it creates a copy
of the reference of that variable into the stack section in memory. Is uses a reference
to get the value. So when the value is changed using the reference it changes the
value of the actual variable.
Example:
#include<iostream>
void my_fun(int &x)
{
x = 50;
cout << "Value of x from my_fun: " << x << endl;
}
main() {
int x = 10;
my_fun(x);
cout << "Value of x from main function: " << x;
}
Output:
Value of x from my_fun: 50
Value of x from main function: 50
An argument is a piece of data (an int value, for example) passed from a program
to the function. Arguments allow a function to operate with different values, or
even to do different things, depending on the requirements of the program calling
50
Chapter 2: Introduction to C++
it. A function without arguments will not work. This can be better understood with
following program. The following program uses three different functions with
same name to handle different number of arguments.
#include <iostream>
using namespace std;
void repchar(char=’*’, int=45); //declaration with
//default arguments
int main()
{
repchar(); //prints 45 asterisks
repchar(‘=’); //prints 45 equal signs
repchar(‘+’, 30); //prints 30 plus signs
return 0;
}
//--------------------------------------------------------------
// repchar()
// displays line of characters
void repchar(char ch, int n) //defaults supplied
{
for(int j=0; j<n; j++) //loops n times
cout << ch; //prints ch
cout << endl;
}
In this program the function repchar() takes two arguments. It’s called three times
from main(). The first time it’s called with no arguments, the second time with one,
and the third time with two. Why do the first two calls work? Because the called
function provides default arguments, which will be used if the calling program
doesn’t supply them. The default arguments are specified in the declaration for
repchar():
void repchar(char=’*’, int=45); //declaration
51
OBJECT ORIENTED PROGRAMMING
The default argument follows an equal sign, which is placed directly after the type
name. You
can also use variable names, as in
void repchar(char reptChar=’*’, int numberReps=45);
If one argument is missing when the function is called, it is assumed to be the last
argument. The repchar() function assigns the value of the single argument to the ch
parameter and uses the default value 45 for the n parameter. If both arguments are
missing, the function assigns the default value ‘*’ to ch and the default value 45 to
n. Thus the three calls to the function all work, even though each has a different
number of arguments.
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
52
Chapter 2: Introduction to C++
Ref. Geeksforgeeks
In the above program, we can see print function thrice. However, the function
print()looks different in all three cases. No. of parameters used in each function is
different. Whenever we call print function and pass parameters or arguments, the
respective function is being called and executed.
we know that, we can pass any type of arguments within the member function and
there are any numbers of arguments. In C++ programming language, we can also
pass an object as an argument within the member function of class. This is useful,
when we want to initialize all data members of an object with another object, we
can pass objects and assign the values of supplied object to the current object. For
complex or large projects, we need to use objects as an argument or parameter.
Example:
#include <iostream>
class Demo
private:
int a;
public:
void set(int x)
a = x;
a = ob1.a + ob2.a;
void print()
53
OBJECT ORIENTED PROGRAMMING
cout<<"Value of A : "<<a<<endl;
};
int main()
//object declarations
Demo d1;
Demo d2;
Demo d3;
d1.set(10);
d2.set(20);
d3.sum(d1,d2);
d1.print();
d2.print();
d3.print();
return 0;
Output:
Value of A: 10
Value of A: 20
Value of A: 30
54
Chapter 2: Introduction to C++
A static member is shared by all objects of the class. All static data is initialized to
zero when the first object is created, if no other initialization is present. We can't
put it in the class definition but it can be initialized outside the class as done in the
following example by re-declaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.
Example:
#include <iostream>
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
55
OBJECT ORIENTED PROGRAMMING
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}
Output:
Constructor called.
Constructor called.
Total objects: 2
A static member function can only access static data member, other static member
functions and any other functions from outside the class. Static member functions
have a class scope and they do not have access to the this pointer of the class. You
could use a static member function to determine whether some objects of the class
have been created or not.
Example:
include <iostream>
class Box
{
public:
static int objectCount;
// Constructor definition
56
Chapter 2: Introduction to C++
57
OBJECT ORIENTED PROGRAMMING
Output:
Initial Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
3. Function overloading can be done using the same function name using
different parameters.
Web references:
1. https://dev.mysql.com
2. www.github.com
3. Geeksforgeek.com
2.15 Bibliography
58
Chapter 2: Introduction to C++
59
UNIT 2
3
INTRODUCTION TO C++ -
CONSTRUCTOR & ARRAY
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Constructor
3.2.1 Default
3.2.2 Parameterized
3.2.3 Copy
3.2.4 Constructor Overloading
3.2.5 Destructor
3.3 Array
3.3.1 Array as a Class member
3.3.2 Array of objects
3.3.3 Strings – C Style strings
3.3.4 String Class
3.4 Let us sum up
3.5 List of references
3.6 Bibliography
3.7 Unit end exercise
3.0 Objectives
After the completion of this unit, you will be able to understand following things,
1. Constructor, its functions and its types.
2. Introduction to array & types of array.
60
Chapter 3: Introduction to C++ - Constructor & Array
Definition:We know that an object can initialize itself when it’s first created,
without requiring a separate call to a member function. Automatic initialization is
carried out using a special member function called a constructor. A constructor is
a member function that is executed automatically whenever an object is created.
Constructor
Syntax: The name of the constructor is same the name of function. Default
constructor doesn’t take any argument, that means it has no parameters.The syntax
is more or less same all the three, let us have a look at Default constructor with
following example.
Example:
#include<iostream>
class construct {
public:
int a, b;
61
OBJECT ORIENTED PROGRAMMING
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20
In the above program, Function ‘construct’ has been defined with a default
constructor named ‘construct’. Two values of ‘a’ and ‘b’ have been defined inside
the function. This means if user doesn’t pass any value, default constructor would
be called automatically. In the main() method we can see, once the object created
for the function construct, values from the default constructor are called and
displayed as the output.
3.2.2Parameterized Constructor
62
Chapter 3: Introduction to C++ - Constructor & Array
Syntax: The syntax is same as default constructor but with parameters. So the name
of the constructor will remain same as per the logic, we will add parameters to it.
Example:
#include <iostream>
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point (int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
63
OBJECT ORIENTED PROGRAMMING
return 0; }
Output:
P1.x = 10, P1.y = 15
In the above program, we can see the use of Parameterized constructor. The name
of the parameterised constructor is same as the class name and it has 2 parameters.
Once called in main() method using an object with parameters, the call is made to
the parameterised constructor and values are displayed accordingly.
It is a member function which initializes an object using another object of the same
class. Whenever we define one or more non-default constructors (with parameters)
for a class, a default constructor (without parameters) should also be explicitly
defined as the compiler will not provide a default constructor in this case. However,
it is not necessary but it’s considered to be the best practice to always define a
default constructor.
Syntax:
64
Chapter 3: Introduction to C++ - Constructor & Array
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
In C++, we can have more than one constructor in a class with same name, as long
as each has a different list of arguments. This concept is known as Constructor
Overloading and is quite similar to function overloading.
Things to remember!
1. Overloaded constructors essentially have the same name (name of the class)
and different number of arguments.
2. A constructor is called depending upon the number and type of arguments
passed.
3. While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called.
Example:
#include <iostream>
class construct
{
public:
float area;
// Constructor with no parameters
65
OBJECT ORIENTED PROGRAMMING
construct()
{
area = 0;
}
// Constructor with two parameters
construct(int a, int b)
{
area = a * b;
}
void disp()
{
cout<< area<< endl;
}
};
int main()
{
construct o;
construct o2(10, 20);
o.disp();
o2.disp();
return 1;
}
Output: 0
200
In the above example, two constructors were declared and defined. 1 with no
parameters & other with parameters. You already know that the constructor without
parameter is the default constructor whereas the other constructor is parameterized.
When the objects are created and are called in main() method, the object with no
parameter will point to default constructor and the other object with parameters will
66
Chapter 3: Introduction to C++ - Constructor & Array
3.2.5 Destructor
As constructor is defined to create and execute the program using object, destructor
is used to delete an object.
A destructor function is called automatically when the object goes out of scope:
1. the function ends
2. the program ends
3. a block containing local variables ends
4. a delete operator is called
Remember destructor neither take any argument nor return anything. It can be
used using tilde(~) sign.
Consider a scenario where we need to find out the average of 50 integer numbers
entered by user. We can do this in two ways in C:
1) Declare & define 50 variables with integer data type and then perform 50
scanf() operations to store the entered values in the variables and then at last
calculate the average of them.
2) Or have a single integer array to store all the values, loop the array to store
all the entered values in array and later calculate the average.
Of course the second solution is convenient because it will not only reduce
the number of Lines of coding but also its easy to store data of similar data
type.
They are used to store similar type of elements as in the data type must
be the same for all elements.
They can be used to store collection of primitive data types such as int,
float, double, char or they can be any user-defined types such as
structures and objects.
67
OBJECT ORIENTED PROGRAMMING
Arrays are like structures in that they both group a number of items into
a larger unit. But while a structure usually groups items of different
types, an array groups items of the same type.
Example:
#include <iostream>
int main()
{
int age[4];
for(int j=0; j<4; j++) //get 4 ages
{
cout << “Enter an age: “;
cin >> age[j]; //access array element
}
68
Chapter 3: Introduction to C++ - Constructor & Array
Arrays can be used as data items in classes. Let’s take an example of a common
computer data structure: the stack.
A stack works like the spring-loaded devices that hold trays in cafeterias.
When you put a tray on top, the stack sinks down a little; when you take a
tray off, it pops up.
The last tray placed on the stack is always the first tray removed.
Program:
#include <iostream>
class Stack
{
private:
69
OBJECT ORIENTED PROGRAMMING
70
Chapter 3: Introduction to C++ - Constructor & Array
In the above program, when an item is added to the stack, the index in top is
incremented to point to the new top of the stack. When an item is removed, the
index in top is decremented. To place an item on the stack—a process called
pushing the item—you call the push() member function with the value to be stored
as an argument. To retrieve (or pop) an item from the stack, you use the pop()
member function, which returns the value of the item.
The main() method in above program exercises the stack class by creating an
object, s1, of the class. It pushes two items onto the stack, and pops them off and
displays them. Then it pushes four more items onto the stack, and pops them off
and displays them.
Output:
1: 22
2: 11
3: 66
4: 55
5: 44
6: 33
3.3.2Array as objects
We’ve seen how an object can contain an array. We can also reverse that situation
and create an array of objects.
Program:
#include <iostream>
class Distance
{
private:
int feet;
float inches;
public:
void getdist() //get length from user
{
cout << “\n Enter feet: “; cin >> feet;
71
OBJECT ORIENTED PROGRAMMING
Output:
72
Chapter 3: Introduction to C++ - Constructor & Array
In this program the user types in as many distances as desired. After each distance
is entered, the program asks if the user desires to enter another. If not, it
terminates, and displays all the distances entered so far.
We noted at the beginning of this chapter that two kinds of strings are commonly
used in C++: C-strings and strings that are objects of the string class. We call these
strings C-strings, or C-style strings, because they were the only kind of strings
available in theC language.
They may also be called char* strings, because they can be represented as pointers
to type char. Although strings created with the string class, havesuperseded C-
strings in many situations, C-strings are still important for a variety of reasons.First,
they are used in many C library functions. Second, they will continue to appear in
legacy code for years to come. And third, for students of C++, C-strings are more
primitive andtherefore easier to understand on a fundamental level.
Standard C++ includes a new class called string. This class improves on the
traditional C-stringin many ways. For one thing, you no longer need to worry about
creating an array of theright size to hold string variables.
73
OBJECT ORIENTED PROGRAMMING
The string class assumes all the responsibility for memory management. Also, the
string class allows the use of overloaded operators, so you can concatenate string
objects with the + operator:
s3 = s1 + s2
There are other benefits as well. This new class is more efficient and safer to use
than C-strings were. In most situations it is the preferred approach. In this section
we’ll examine the string class and its various member functions and operators.
You can define a string object in several ways. You can use a constructor with no
arguments,creating an empty string. You can also use a one-argument constructor,
where the argument is a C-string constant; that is, characters delimited by double
quotes. As in our homemade String class, objects of class string can be assigned
to one another with a simple assignment operator.
Program:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1(“Man”); //initialize
string s2 = “Beast”; //initialize
string s3;
s3 = s1; //assign
cout << “s3 = “ << s3 << endl;
s3 = “Neither “ + s1 + “ nor “; //concatenate
s3 += s2; //concatenate
cout << “s3 = “ << s3 << endl;
s1.swap(s2); //swap s1 and s2
cout << s1 << “ nor “ << s2 << endl;
return 0;
}
74
Chapter 3: Introduction to C++ - Constructor & Array
Output:
s3 = Man
s3 = Neither Man nor Beast
Web references:
1. https://dev.mysql.com
2. www.github.com
3. Geeksforgeek.com
3.6 Bibliography
75
OBJECT ORIENTED PROGRAMMING
76
UNIT 3
4
OPERATOR OVERLOADING
Unit Structure
4.0 Objective
4.1 Operator Function-Introduction
4.2 Implementing Operator Overloading
4.2.1 Member Function
4.2.2 Non Member Function
4.2.3 Friend Function
4.3 Unary Operator Overloading
4.4 Binary Operator Overloading
4.5 Overloading Subscript Operator
4.6 Type Conversion Operators
4.6.1 Primitive to Object
4.6.2 Object to Primitive
4.6.3 Object to Object
4.7 Advantages
4.8 Drawbacks
4.9 Summary
4.10 Unit End Exercise
4.11 Further Readings
4.0 Objective
77
OBJECT ORIENTED PROGRAMMING
C++ offers a rich collection of operators in its basket. Some of those operators we
have already covered in the previous units. One of the enriching feature offered by
C++ is known as operator overloading. Modern day most of the programming
languages makes use of this feature in order to support OOP features.
For example, we all are aware that an addition operator (+) is essentially a numeric
operator and therefore, requires two number operands. The significance of this
operator is to add the numeric values at either side of operator and compute the
summation of the numeric values. Interestingly, the same addition operator (+)
cannot be used in adding two strings. However, if we provide special meaning to
addition operator (+) we can extend the operation of addition operator to include
string concatenation. Consequently, the addition operator would work as follows:
string s1=“LAP”;
string s2=“TOP”;
string s3=s1+s2;
cout<<s3;
Output
LAPTOP
Syntax:
<return_type> operator <operator_being_overloaded>(<argument list>);
where, operator is the keyword and is preceded by the return_type of the operation.
78
Chapter 4: Operator Overloading
Note: In order to overload the addition operator (+) to perform the concatenation
of two characters, the following declaration, which could be either member or
friend function, would be essential
char * operator + (char *s2);
In the first case, operator overloading function can be a member function if and
only if there exist a condition in which Left operand is an Object of that class. In
the second case, if the Left operand is different than the one which we have defined
above, then Operator overloading function must be a non-member function. Third
case is only possible only when there is a condition when there is a need to access
to the private and protected members of class. We will examine each of the above
case in detail.
79
OBJECT ORIENTED PROGRAMMING
While overloading the operator by using this technique, the following points
we need to consider
i. The overloaded operator must be added as a member function of the
left operand.
ii. The left operand becomes the implicit *this object
iii. All other operands become function parameters.
Let us look at the example which will make the understanding slightly more
simpler.
#include <iostream>
class ABC
{
private:
int m_abc;
public:
ABC(int abc) { m_abc = abc; }
80
Chapter 4: Operator Overloading
int main()
{
ABC a1(6);
ABC a2 = a1 + 2;
std::cout << "I have " << a2.getABC() << " rupees.\n";
return 0;
}
A non-member operator overloading function simply has the right name and
does whatever you want.
For example, suppose we add two BitMoney objects and get a third BitMoney
object that has the sum from the first two, etc.
Let's use the example version of BitMoney in which the member variables
n,d, etc., are private.
This function creates a new object, gets the n value from the lhs and rhs
objects, and sets the n of the new object to their sum.
81
OBJECT ORIENTED PROGRAMMING
The "x1 + x2" will be compiled into a call to our operator+ function that takes
two BitMoney objects as arguments. It returns an object containing the sum,
whose values then get copied into x3. The above statements can be rewritten
as follows:
x3 = x1 + x2;
x3 = operator+ (x1, x2);
Please note that these functions are not a members of the class and they there
is no ‘this’ pointer concept.
While overloading unary operator using friend function, you need to pass one
argument whereas for binary operator, one need to pass two arguments.
Syntax:
#include<iostream>
using namespace std;
class UF
{
int x=10;
int y=20;
int z=30;
82
Chapter 4: Operator Overloading
public:
void getv()
{
cout<<"Values of X, Y & Z\n";
cout<<x<<"\n"<<y<<"\n"<<z<<"\n"<<endl;
}
void display()
{
cout<<x<<"\n"<<y<<"\n"<<z<<"\n"<<endl;
}
void friend operator -(UF &a); //Pass by reference
};
void operator-(UF &a)
{
a.x = -a.x; //Object name must be used as it is a friend function
a.b = -a.b;
a.c = -a.c;
}
int main()
{
UF a1;
a1.getv();
cout<<"Before Unary Overloading\n";
a1.display();
cout<<"After Unary Overloading \n";
-a1;
a1.display();
return 0;
}
83
OBJECT ORIENTED PROGRAMMING
Output:
Values of X, Y & Z
10
20
30
Before Unary Overloading
10
20
30
After Unary Overloading
-10
-20
-30
Analysis of program
In the above program, operator – is overloaded using friend function. The
operator() function is defined as a Friend function. The statement -a1 invokes the
operator() function. The object a1 is created of class UF. The object itself acts as a
source and destination object. This can be accomplished by sending reference of an
object. The object a1 is a reference of object a. The values of object a1 are replaced
by itself by applying negation.
84
Chapter 4: Operator Overloading
85
OBJECT ORIENTED PROGRAMMING
Note: In most cases, unary operators operate on the object for which they were
called and normally, this can be done using prefix such as !obj, -obj, and ++obj but
sometime they can also used as postfix as well like obj++ or obj--.
Let us take an example to understand how unary minus (-) operator can be
overloaded for prefix as well as postfix usage.
Program:
#include <iostream>
using namespace std;
class ABC {
private:
int f; // 0 to infinite for measurement in feet
int in; // 0 to 12 for measurement in inches
public:
// required constructors
ABC() {
f = 0;
in = 0;
}
ABC(int feet, int inches) {
f=feet;
inches=i;
}
86
Chapter 4: Operator Overloading
87
OBJECT ORIENTED PROGRAMMING
In the former case, the function takes single argument, whereas in the latter
case it takes two arguments.
Let us understand the concept much better by using the following program.
One can use binary operators very often such as addition (+) operator,
subtraction (-) operator and division (/) operator.
Program:
#include <iostream>
using namespace std;
class ABC {
double l; // l=Length of a box
double b; // b=Breadth of a box
double h; //h= Height of a box
public:
double getVol (void) {
return l * b * h;
}
88
Chapter 4: Operator Overloading
// abc1 specification
abc1.setL(6.0);
abc1.setB(7.0);
abc1.setH(5.0);
// abc2 specification
abc2.setL(6.0);
abc2.setB(7.0);
abc2.setH(5.0);
// volume of abc 1
vol = abc1.getVol();
cout << "Volume of ABC1 : " << vol <<endl;
// volume of abc 2
vol = abc2.getVol();
cout << "Volume of ABC2 : " << vol <<endl;
89
OBJECT ORIENTED PROGRAMMING
// volume of box 3
vol = abc3.getVol();
cout << "Volume of ABC3 : " << vol <<endl;
return 0;
}
After executing the program, it produces the following result −
Volume of ABC1 : 210
Volume of ABC2 : 1560
Volume of ABC3 : 5400
Similarly relational such as (<, >, <=, >=, ==, etc.) operator can be overloaded
which can also be used to compare C++ built-in data types.
Let us take an example which explains how a < operator can be overloaded.
Similar logic can also be applied to overload other relational operators.
#include <iostream>
using namespace std;
class DistDemo {
private:
int f; // 0 to infinite
int in; // 0 to 12
public:
// required constructors
DistDemo() {
f = 0;
in = 0;
}
DistDemo (int feet, int inch) {
f = feet;
in = inch;
}
90
Chapter 4: Operator Overloading
void displayDist() {
cout << "F: " << f << " I:" << in <<endl;
}
91
OBJECT ORIENTED PROGRAMMING
This operator is mainly used with arrays to retrieve and manipulate the
elements of an array.
This operator is generally of the type of binary or n-ary and is denoted as:
1. postfix/primary expression
2. expression
Syntax:
postfix-expression[expression];
Example:
RamLaxman[10];
Here the RamLaxman is an array and the above statement print the value which is
held by RamLaxman at index position 10.
Note: The postfix expression followed by the subscript operator is the pointer and
it can be an integral value but the one must keep in mind that one of expression
among two expressions must be a pointer value and it does not matter whether the
second one is of an integral order or not.
92
Chapter 4: Operator Overloading
OUTPUT
a
a
Explanation:
In the above example both “cout” statement provides similar output due to the
exclusive property of the subscript operator. The compiler reads both the statement
in a similar way, so there is no difference between the *(name + 5) and the *(5 +
name).
However, we know that C++ supports both positive and negative subscripts.
Please note that the Negative subscripts must fall within array boundaries;
if they do not, the results are highly unpredictable.
#include <iostream>
using namespace std;
// Driver Method
int main()
{
int intArr[1024];
93
OBJECT ORIENTED PROGRAMMING
// 512
cout << intArr[512] << endl;
// 257
cout << 257 [intArr] << endl;
// 256
cout << midArr[-256] << endl;
Note: In the above program, the negative subscript in the last line can produce a
run-time error since it points to an address position at -256 positions which can be
lower in memory and violates the origin of the array. The pointer midArr is
specifically initialized to the middle of intArr; to derive the use of both positive and
negative array indices simultaneously. Array subscript errors fails to generate
compile-time errors, but instead they might yield unpredictable results.
In C++, type conversion is a technique which allows one to convert the data
from one form to another.
94
Chapter 4: Operator Overloading
C++ has a rich collection of data types ranging from the basic (primitive) data
types to the User Defined (Object) data types.
In this section, we are going to learn about the conversion of these data types
from one form to other.
For example,
int x1;
float x2 = 0.316;
In order to assign the value of float to x1, we can write
x1= x2;
Note: When the above code is compiled, the compiler will not generate any
error(x1 is of integer type whereas x2 is of float type) and instead it will be handled
implicitly by running some internal routine to convert the float value to integer.
However the programmer can also give commands to the compiler by writing
code to convert the float type to integer type. This type of conversion is
known as explicit conversion of basic type data.
Let us understand the concept much better by using the following program.
Program:
#include <iostream>
#include <string>
using namespace std;
void main(void) {
int x1;
float x2 = 5.825;
95
OBJECT ORIENTED PROGRAMMING
x1=x2;
cout<<x1;
}
Output:
Program analysis
In the above program, we have declared two variables, x1 of type integer and x2 of
type float and we initialized float with value 5.825. As we have stored the value of
float variable in integer variable by using equals sign operator. In this the compiler
does run the conversion routine automatically and stock the integer type value of
float into integer variable.
Conversion from primitive to object data type can be best explained with the
help of code.
Consider a class called Dist which will have values in meters to distance
class; where meter is a float type primitive type and distance is an object data
class.
Dist = float;
In the above statement we will be storing float values in distance class and
will show it.
96
Chapter 4: Operator Overloading
Program:
#include <iostream>
using namespace std;
const float MTF=3.280;
class Dist {
int f;
float in;
public:
Dist() //Distance Constructor {
f=0;
in=0.0;
}
Dist(float nom) //Single Parameter constructor {
float fif= MTF * nom;
f=int(fif);
in=12*(fif-f);
}
void showdist() // Method to display converted values {
cout<<"Converted Value is: "<<f<<"\' feets and "<<in<<'\"'<<"
inches.";
}
};
int main() {
cout <<"Float to distance
conversion.\n********************************\n";
float m;
cout<<"Enter values in meter:";
cin >>m;
Dist dist = m;
dist.showdist();
}
97
OBJECT ORIENTED PROGRAMMING
Output:
Float to distance conversion
*********************************
Program analysis:
In the above program, class Dist is created with two member variables:
integer type ‘f’ and float type ‘in’.
A no argument constructor is created which will initialize the values of f and
in to 0 and 0.0 respectively.
Next, it has a constructor that takes a float type variable as an argument.
Within this constructor, we multiply the passed float type variable with
3.280833 which is stored in constant MTF variable.
Next, we will multiply the passed float parameter with this number because
passed variable will contain meters. And one meter contains 3.280833.
In the above program,class Dist has distance expressed in feet and inches,
therefore we converted the float to feet. Then we truncated the decimal part
of the feet using
f=int(fif)
In C++, while doing conversion from Object type to Primitive type, a whole
new concept is involved in this conversion called as overloading casting
operator.
operator type()
{
.
.
.
}
98
Chapter 4: Operator Overloading
This kind of function will have no return type and without any arguments.
The ‘operator’ is the keyword that has to be used followed by basic data type.
Let us understand this by example. If one needs to overload the float operator
can be done by operator float() {}.
#include <iostream>
using namespace std;
const float MTF=3.280833;
// Meter to feet
class Dist {
int f;
float in;
public:
Dist() // Default Constructor {
f=0;
in=0.0;
}
Dist(int ft, float inc) //two arguements constructor {
f=ft;
in=inc;
}
99
OBJECT ORIENTED PROGRAMMING
Output:
Enter the distance in Feet and Inches:
Feet: 22.96
Inches: 275.59
Converted Distance in Meters is: 7
Program analysis
The logic is applied inside this operator definition, to merge feet and inches
to get a consolidate value in meters.
100
Chapter 4: Operator Overloading
float FIF=in/12;
Next, we need to divide this value by MTF variable which contains value
3.280833.
In this type of conversion, one can assign data that belongs to a particular
class type to an object that belongs to another class type.
Let us create two classes ‘X’ and ‘Y’. In order to allocate the details that
belong to class ‘X’ to an object of class ‘Y’ then this can be defined by –
Program:
#include <bits/stdc++.h>
using namespace std;
class Demo {
string x = "Hello World";
public:
string get_str ()
{
return (x);
}
void display()
{
cout << x << endl;
}
};
class Demo1 {
string y;
public:
101
OBJECT ORIENTED PROGRAMMING
Output:
Hello World
Hello World
4.7 Advantages
Operator overloading allow the C++ developers to use notation closer to the
target domain. For example we can subtract two matrices by writing X1 - X2
rather than writing X1.subtract(X2).
Operator overloading provides consistent syntactic support of right from
built-in types till user-defined types.
The basic goal is to make programs easier to understand.
102
Chapter 4: Operator Overloading
4.8 Drawbacks
There are some limitations on operator overloading that are not very important for
the practicing programmer, at least not at this stage.
4.9 Summary
In this unit, we have seen how the normal C++ operators can be given new
meanings when applied to user-defined data types.
1. Overload the addition operator (+) to assign binary addition. The following
operation should be supported by +.
110010 + 011101 = 1001111
103
OBJECT ORIENTED PROGRAMMING
x=y;
cout<<x;
cout<<y;
4. What are the differences between overloading a unary operator and that of a
binary operator? Illustrate with suitable examples.
104
Chapter 4: Operator Overloading
#include <iostream>
#include <string>
using namespace std;
class complex
{
int i;
int j;
public:
complex(int a, int b)
{
i = a;
j = b;
}
complex operator+(complex c)
{
complex temp;
temp.i = this->i + c.i;
105
OBJECT ORIENTED PROGRAMMING
d) Segmentation fault
#include <iostream>
#include <string>
using namespace std;
class complex
{
int i;
int j;
public:
complex(){}
complex(int a, int b)
106
Chapter 4: Operator Overloading
{
i = a;
j = b;
}
complex operator+(complex c)
{
complex temp;
temp.i = this->i + c.i;
temp.j = this->j + c.j;
return temp;
}
void show(){
cout<<"Complex Number: "<<i<<" + i"<<j<<endl;
}
};
int main(int argc, char const *argv[])
{
complex c1(1,2);
complex c2(3,4);
complex c3 = c1 + c2;
c3.show();
return 0;
}
a) Complex Number: 4 + i6
b) Complex Number: 2 + i2
c) Error
d) Segmentation fault
#include <iostream>
#include <string>
using namespace std;
class complex
{
107
OBJECT ORIENTED PROGRAMMING
int i;
int j;
public:
complex(){}
complex(int a, int b)
{
i = a;
j = b;
}
complex operator+(complex c)
{
complex temp;
temp.i = this->i + c.i;
temp.j = this->j + c.j;
return temp;
}
void operator+(complex c)
{
complex temp;
temp.i = this->i + c.i;
temp.j = this->j + c.j;
temp.show_poss();
}
void show(){
cout<<"Complex Number: "<<i<<" + i"<<j<<endl;
}
void show_poss(){
cout<<"Your result after addition will be: "<<i<<" + i"<<j<<endl;
}
};
108
Chapter 4: Operator Overloading
#include <iostream>
#include <string>
using namespace std;
class Box{
int capacity;
public:
Box(){}
Box(double capacity){
this->capacity = capacity;
}
};
int main(int argc, char const *argv[])
{
Box b1(10);
Box b2 = Box(14);
if(b1 == b2){
cout<<"Equal";
}
109
OBJECT ORIENTED PROGRAMMING
else{
cout<<"Not Equal";
}
return 0;
}
a) +
b) ==
c) =
d) ()
9. Give the function prototype of the operator function which we need to define
in this program so that the program has no errors.
#include <iostream>
#include <string>
using namespace std;
class Box{
int capacity;
public:
Box(){}
Box(double capacity){
this->capacity = capacity;
}
};
int main(int argc, char const *argv[])
{
Box b1(10);
Box b2 = Box(14);
if(b1 == b2){
cout<<"Equal";
}
else{
cout<<"Not Equal";
}
return 0;
}
a) bool operator==();
b) bool operator==(Box b){}
110
Chapter 4: Operator Overloading
111
OBJECT ORIENTED PROGRAMMING
Books
1. E Balagurusamy; Object-Oriented Programming with C++; Tata Mc Graw-
Hill.
2. Herbert Schildt; The Complete Reference C++; Tata McGraw Hill.
3. Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
4. Object Oriented Programming using C++-Lovely Professional University
notes
Online links
1. http://www.mochima.com/tutorials/strings.html
2. http://www.exforsys.com/tutorials/c-plus-plus/operator-overloading-
partii.html
3. https://www.geeksforgeeks.org/c-operator-overloading-question-1/
4. https://www.sanfoundry.com/cplusplus-programming-questions-answers-
operator-overloading-2/
5. https://www.geeksforgeeks.org/overloading-subscript-or-array-index-
operator-in-c/
112
UNIT 3
5
POINTERS IN C++
Unit Structure
5.0 Objective
5.12 Summary
113
OBJECT ORIENTED PROGRAMMING
5.0 Objective
Pointers
They have data type just like variables, for example an integer type pointer
can hold the address of an integer variable and an character type pointer can
hold the address of char variable.
114
Chapter 5: Pointers in C++
Let “p” be the pointer variable which holds the address of variable num.
Thus, we can access the value of “number” by the pointer variable ‘p’. Thus,
we can say “p points to number”.
Note that the actual address of a variable in memory will be known only at
the execution of the code.
To simplify the things, let us assume the variable “a” is placed during runtime
in the memory address 1776.
1 a = 25;
2
x = &a;
3
y = a;
115
OBJECT ORIENTED PROGRAMMING
The diagram below depicts the values assigned in each of the variable after
execution of the code.
One striking difference between the second and third statements are the
position of address-of operator(&)
Note that in C++, if we have a variable which will store the address of another
variable (like x in the previous example) we call such variables as a pointer.
Pointers are a very influential feature of any programming language that has
many uses in lower level programming. A bit later, we will see many different
types of pointers.
Syntax:
data_type (*var_name)[size_of_array];
where var_name-> name of the pointer variable
116
Chapter 5: Pointers in C++
In the above program, pointer variable(ptr) which points to the 0th element of
the array. Instead of declaring a pointer which points to only one element, we
can declare a pointer which can point to whole array This is called as array
of pointer.
Example:
int (*ptr)[5];
Program:
#include <iostream>
using namespace std;
int main()
{
// Pointer to an integer
117
OBJECT ORIENTED PROGRAMMING
int *x;
x: is pointer to 0th element of the array a, while ptr is a pointer that points to
the whole array a.
The base type of x is int while base type of ptr is ‘an array of 5 integers’.
Please note that if we write ptr++, then the pointer ptr will be shifted ahead
by 20 bytes.
118
Chapter 5: Pointers in C++
In the above statement, we have created an array of pointer named as ptr, and
it allocates 10 integer pointers in memory.
In the above code, we are assigning the address of 'x' variable to the second
element of an array 'ptr'.
1. *ptr[1];
119
OBJECT ORIENTED PROGRAMMING
for(int i=0;i<15;i++)
{
std::cin >> ptr1[i];
}
for(int i=0;i<15;i++)
{
ptr2[i]=&ptr1[i];
}
// printing the values of ptr1 array
std::cout << "The values are" << std::endl;
for(int i=0;i<15;i++)
{
std::cout << *ptr2[i] << std::endl;
}
}
In the above program, we declare an two arrays. i.e; one of integer type and
second of integer pointers. We have used the 'for' loop, which iterates through
the elements which are the part of an array 'ptr1'.
Please note on each iteration, the address of element of ptr1 at index 'i' gets
stored in the ptr2 at index 'i'.
Let us consider, we have a ptr which is of integer type pointer which points
to the address 5000.
If we now perform ptr++, the pointer will now point to location 5004(4 bytes
of memory reserved for integers). The best part of this is that though it allows
to shift to new location in array, it absolutely makes no changes to the value
stored at a given location.
120
Chapter 5: Pointers in C++
1. Incrementing a Pointer
#include <iostream>
using namespace std;
const int MAX = 5;
int main () {
int v[MAX] = {50, 100, 150, 200, 250};
int *ptr;
// let us have array address in pointer.
ptr = v;
for (int i = 0; i < MAX; i++) {
cout << "Address =”<<ptr << endl;
cout << "Value = "<<i<<endl;
cout << *ptr << endl;
ptr++; //increments to new location
}
return 0;
}
On successful compilation and execution of the above code, it produces output
as follows −
121
OBJECT ORIENTED PROGRAMMING
Address= 0xbfa088b0
Value = 50
Address = 0xbfa088b4
Value = 100
Address = 0xbfa088b8
Value = 150
Address = 0xbfa088b12
Value = 200
Address = 0xbfa088b16
Value = 250
2. Decrementing a Pointer
Program:
#include <iostream>
using namespace std;
const int MAX = 5;
int main () {
int v[MAX] = {50, 100, 150, 200, 250};
int *ptr;
// let us have address of the last element in pointer.
ptr = &v[MAX-1];
122
Chapter 5: Pointers in C++
We use const keyword before declaring the datatype and variable name. Let
us see the example.
123
OBJECT ORIENTED PROGRAMMING
1 int v = 5;
3 v = 6;
1 int v = 5;
3 *ptr = 6; //
Note: The above statements are invalid as a pointer to a const value is not const
itself, thus enabling the pointer to be redirected to point at other values.
We know that a const pointer is a pointer whose value are fixed after
initialization
int v = 15;
int *const ptr = &v;
124
Chapter 5: Pointers in C++
We are also aware that a const pointer must be initialized to a some known
value upon declaration. Please keep in mind that a const pointer will always
point to the same address.
In the above case, ptr will always point to the address of value until it is
destroyed or goes out of scope.
int v1 = 15;
int v2 =16;
int * const ptr = &v1; //allowed
ptr = &v2; //not allowed
One can change the value being pointed by implementing dereferencing the
const pointer as given below
int v = 15;
int *const ptr = &v; //allowed
*ptr = 16; //allowed
Now let us begin with how to declare and initialize a pointer variable. The
general form of a pointer variable is given by
Syntax:
datatype *pointer_name;
Please note that the Data type of a pointer and the data type of the variable to
which the pointer variable is pointing should be the same and cross data types
are not allowed here.
The exception to this is void type pointer which works with all data types,
but is rarely used.
125
OBJECT ORIENTED PROGRAMMING
Please note that pointer variables always point to variables of same datatype.
Consider the following example:
#include<iostream.h>
void main()
{
float x;
int *ptr;
ptr = &x; // ERROR, type mismatch
}
Please remember to assign a NULL value to your pointer variable If you are not
sure about which variable's address to assign to a pointer variable while performing
declaration of variables. The pointer which has been assigned with a NULL value
is called as a NULL pointer. Consider the example of NULL pointer listed below
#include <iostream.h>
int main()
{
int *ptr = NULL;
return 0;
}
126
Chapter 5: Pointers in C++
#include <iostream.h>
int main()
{
int x, *ptr; // declaring the variable and pointer
x = 10;
ptr = &x; // initializing the pointer
cout<< *ptr; //this will print the value of 'x'
cout<< *&x; //this will also print the value of 'x'
cout<< &x; //this will print the address of 'x'
cout<< ptr; //this will also print the address of 'x'
cout<< &ptr; //this will print the address of 'ptr’
return 0;
}
127
OBJECT ORIENTED PROGRAMMING
They are basically used to hold address of any type and can be converted to
any another type.
int x = 20;
char y = 'a';
void *ptr = &x; // address of int 'x' -> ptr
ptr = &y; // address of char 'y' ->ptr
1) Please note that malloc() and calloc() always return void * type data and
this allows these functions to be used to allocate memory of any data type
(just because of void *)
int main(void)
{
int *a = (int *) malloc(sizeof(int) * p);
}
Points to remember
1. In the above code, we have explicitly typecast return value of malloc to (int
*) as in C++ it is mandatory requirement. This may note be done while
compiling in C language.
They are basically used in the special case where we are not sure about the
exact address to be assigned to a pointer variable.
128
Chapter 5: Pointers in C++
#include <iostream>
using namespace std;
int main () {
int *p = NULL;
cout << "Value of Pointer= " << p;
return 0;
}
Please note that modern day operating systems do not permit programs to
access memory at address 0 as it is reserved by operating system.
It is a practice to make use an if statement in order to check for the null pointer
which is describe as follows −
if(ptr)
if(!ptr)
1. De-allocation of memory
129
OBJECT ORIENTED PROGRAMMING
int main()
{
int *ptr = (int *)malloc(sizeof(int));
free(ptr); //pointer becoming a dangling pointer
// No more a dangling pointer
ptr = NULL;
}
2. Function Call
// The pointer pointing to local variable becomes
// dangling when local variable is not static.
#include<iostream.h>
int *fun()
{
int x1 = 15;
return &x1;
}
// Driver Code
int main()
{
int *p1 = fun();
fflush(stdin);
cout<<*p;
return 0;
}
Output:
A garbage Address
The above problem doesn’t appear (or p doesn’t become dangling) if x is a static
variable.
130
Chapter 5: Pointers in C++
int main()
{
int *p = fun();
fflush(stdin);
Output:
5
3. Variable goes out of scope
4. void main()
5. {
6. int *ptr;
7. .....
8. .....
9. {
10. int ch;
11. ptr = &ch;
12. }
13. .....
14. // Here ptr is dangling pointer
}
131
OBJECT ORIENTED PROGRAMMING
Note: The main responsibility of the programmer here is to deallocate the memory
which is no longer used and hence this is done by using delete operator.
New Operator
When this operator is used, new operator initializes the memory and returns
the address and initialized memory to the pointer variable.
Syntax:
pointer-variable = new data-type;
where, pointer-variable is the pointer of type data-type.
Examples:
1. int *p = new int;
2. int *p = new int(25);
3. float *q = new float(75.25);
Delete Operator
In C++, programmer deallocate the memory dynamically allocated memory
earlier by using delete operator.
Syntax:
delete pointer-variable;
where, pointer-variable -> pointer that points to the data object created by new.
132
Chapter 5: Pointers in C++
Examples:
delete a;
delete b;
5. Example linked list, tree, etc. C++ references cannot be used to implement
these data structures because references are fixed to a particular location.
5.12 Summary
A variable which hold the memory address of the location of another variable
in memory is called as pointer. It can be defined as type * var_name ;
where type is a predefined C++ data type and var_name is the name of the pointer
variable.
The operator &, should be placed before a variable, also returns the memory
address of its operand.
The operator * when used returns the memory address of its operand.
133
OBJECT ORIENTED PROGRAMMING
The operator * returns the data value stored in the area being pointed to by
the pointer following it.
The pointer variables must always point to the correct type of data.
Pointers must be initialized properly because uninitialized pointers
result in the system crash.
An array name is a pointer that stores the address of its first element. If
the array name is incremented, It actually points to the next element of
the array.
4. How can we avoid syntax errors when calling a member function using a
pointer-tomember-function?
{
int x [5], *y [5]
for (i = 0; i< 5; i++)
134
Chapter 5: Pointers in C++
{ x [i] = I;
x[i] = i + 3;
y = z;
x = y;
}
Books
Online links
1. http://www.mochima.com/tutorials/strings.html
2. http://www.exforsys.com/tutorials/c-plus-plus/operator-overloading-
partii.html
3. http://publib.boulder.ibm.com/infocenter/comphelp/v8v101
index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr03
5.htm
4. http://www.cplusplus.com/doc/tutorial/pointers/
135
UNIT 4
6
INHERITANCE AND POLYMORPHISM
Unit Structure
6.0 Objectives
6.1 Introduction
6.2 Inheritance concept
6.3 Derivation of inheritance
6.3.1 Public mode
6.3.2 Private mode
6.3.3 Protected mode
6.4 Types of inheritance :
6.4.1 Single inheritance
6.4.2 Multilevel inheritance
6.4.3 Hierarchical inheritance
6.4.4 Multiple inheritance
6.4.5 Multipath or Hybrid inheritance
6.5 Member hiding
6.6 Function overriding
6.7 Multiple inheritance, Multipath inheritance – Ambiguities and solution
6.8 Constructor and inheritance
6.8.1 Single inheritance
6..8.2Multiple inheritance
6.8.3 Parameterized constructor
6.9 Let us Sum Up
6.10 List of Reference
6.11 Bibliography
6.12 Unit End Exercise
136
Chapter 6: Inheritance and Polymorphism
6.0 Objectives
6.1 Introduction
Inheritance are of different types which reflects different effect on its member
functions depending on its visibility mode
Resuability
Eg the base class is vehicle which is inherited by the train, car and flight
Vehicle
Figure 1. inheritance
137
OBJECT ORIENTED PROGRAMMING
Derived class:The class that inherits properties from another class is called Derived
Class.
Base class: The class whose properties are inherited by derived class is called Base
Class.
#include <iostream>
class base_classname
{
.... ... ....
};
class derived_classname : access_modifiersbase_classname
{
.... ... ....
};
A derived class is derived from a base class with different access control or
modifiers.
#include <iostream.h>
#include <conio.h>
class base
{
int a;
protected:
138
Chapter 6: Inheritance and Polymorphism
int b;
public:
int c;
void get()
{
cout<<"enter 3 nos:";
cin>>a>>b>>c;
}
int get_pri()
{
return a;
}
};
class derived : public base
{
public :
void show()
{
cout<<get_pri()<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
};
void main()
{
clrscr();
derived o;
o.get();
o.show();
getch();
}
139
OBJECT ORIENTED PROGRAMMING
#include <iostream.h>
#include <conio.h>
class base
{
int a;
protected:
int b;
public:
int c;
void get()
{
cout<<"enter 3 nos:";
cin>>a>>b>>c;
}
int get_pri()
{
return a;
}
};
class derived : protected base
{
public :
void show()
{
140
Chapter 6: Inheritance and Polymorphism
base::get();
cout<<get_pri()<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
};
void main()
{
clrscr();
derived o;
o.show();
getch();
}
#include <iostream.h>
#include <conio.h>
//inheritance
/*
class derivedclass : access modifier baseclass
{
members of dc
};
*/
141
OBJECT ORIENTED PROGRAMMING
class base
{
int a;
protected:
int b;
public:
int c;
void get()
{
cout<<"enter 3 nos:";
cin>>a>>b>>c;
}
int get_pri()
{
return a;
}
};
class derived : private base
{
public :
void show()
{
base::get();
cout<<get_pri()<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
};
142
Chapter 6: Inheritance and Polymorphism
void main()
{
clrscr();
derived o;
o.show();
getch();
}
6.4.1 Single Inheritance:when a single derived class is inherited from the single
based class
Syntax :
class derived_classname : access_modifierbase_classname
{
//body of derived class
};
class Animals
{
public:
void commutes()
{
cout<<"yes"<<endl;
}
};
class Horse: public Animal
143
OBJECT ORIENTED PROGRAMMING
{
public:
void numberoflegs()
{
cout<<4;
}
};
int main(void) {
Dog d1;
d1.commutes();
d1.numberoflegs();
return 0;
}
6.4.2 Multilevel inheritance: inherits derived class from another derived class
class derived_classname : access_modifier base_classname1,
access_modifierbase_classname, ....
{
//body
};
include <iostream>
class Animal
{
public:
144
Chapter 6: Inheritance and Polymorphism
void commutes() {
cout<<"yes."<<endl;
}
};
class Horse: public Animal
{
public:
void numberoflegs(){
cout<<"4"<<endl;
}
};
class foal: public Horse
{
public:
void tail() {
cout<<"yes";
}
};
int main(void) {
foal d1;
d1.commutes();
d1.numberoflegs();
d1.tail();
return 0;
}
145
OBJECT ORIENTED PROGRAMMING
{
//body
};
A B
class individual
{
int age;
char name[10];
public:
int c;
void get()
{
cout<<"enter name & age:";
cin>>name>>age;
}
void show()
{
cout<<"name="<<name<<", age="<<age;
}
};
class student
{
int marks;
public :
void get()
{
cout<<"enter marks";
cin>>marks;
}
146
Chapter 6: Inheritance and Polymorphism
void showmarks()
{
cout<<" marks="<<marks;
}
};
class fulltime-student : public individual,public student
{
};
void main()
{
clrscr();
fulltime o;
o.individual::get();//ambiguity resolved
o.student::get();//ambiguity resolved
o.show();
o.showmarks();
getch();
}
A B
#include <iostream>
using namespace std;
class Shape
{
public:
int l;
147
OBJECT ORIENTED PROGRAMMING
int b;
void getdata(int a,int b)
{
l= a;
b = b;
}
};
class Rectangle : public Shape
{
public:
int area_rect()
{
int area = l*b;
return area;
}
};
class Triangle : public Shape
{
public:
int area_triangle()
{
float area = 0.5*l*b;
return area;
}
};
int main()
{
Rectangle r;
Triangle t;
148
Chapter 6: Inheritance and Polymorphism
int length,breadth,base,height;
cout<< "Enter the length and breadth of a rectangle: " ;
cin>>length>>breadth;
r.getdata(length,breadth);
int result_rect = r.area_rect();
cout<< "Area of the rectangle is : ";
cout<< "Enter the base and height of the triangle: " ;
cin>>base>>height;
t.getdata(base,height);
float result_tri = t.area_triangle();
cout<<"Area of the triangle is : " ;
return 0;
}
A B
D
class emp
{
int age;
char name[10];
public:
int c;
void get()
{
cout<<"enter name & age:";
cin>>name>>age;
}
149
OBJECT ORIENTED PROGRAMMING
void show()
{
cout<<"name="<<name<<" age="<<age;
}
};
class fulltime : public emp
{
int sal;
public :
void getsal()
{
cout<<"enter sal";
cin>>sal;
}
void showsal()
{
cout<<" sal="<<sal;
}
};
class contract : public emp
{
int workinghrs;
int wagesper_hr;
public:
void gethr_wage()
{
cout<<"enter working hrs & wages per hr";
cin>>workinghrs>>wagesper_hr;
}
void showcal_sal()
{
cout<<" Total salary="<<workinghrs*wagesper_hr;
}
};
class performance:publicfulltime,public contract
{
int score;
150
Chapter 6: Inheritance and Polymorphism
public:
void getscore()
{
cout<<"enter score";
cin>>score;
}
void showscore()
{
cout<<" rating="<<score;
}
};
void main()
{
clrscr();
cout<<"\nEnter Fulltime emp data"<<endl;
fulltime f;
f.get();
f.getsal();
performance p;
p.getscore();
f.show();
f.showsal();
p.showscore();
cout<<"\nEnter Contract emp data"<<endl;
performance p1;
p1.contract::get();
p1.getsal();
p1.getscore();
p1.contract::show();
p1.showsal();
p1.showscore();
getch();
}
151
OBJECT ORIENTED PROGRAMMING
In Method Hiding takes place when the derived class has function with same
name as that of the function in base class, then the derived class function will
hide all base class function with same name even if the signatures are
different.
Method hiding gives a different implementation to the base class method with
the change in signature
To avoid the base class method form getting hidden, the scope resolution
operator is used along with the base class name
#include <iostream>
class Base
{
public:
void fun()
{
cout<<”void”<<endl;
}
Int fun(int a, int b)
{
cout<<”base”<<endl;
}
};
class Derived: public Base
{
public:
void fun (char c)
{
152
Chapter 6: Inheritance and Polymorphism
cout<<"Derived Class";
}
};
Int main()
{
Derived d;
d.fun(‘a’);
d.Base::fun(2);
return(0);
}
If derived class defines a function with same name as defined in the base class
then it is known as function overriding.
the function in base class is called the overridden function and function in
derived class is called as overriding function.
In static binding, the pointer of type base class will call function inside the
base class inspite it is made pointing to derived class
The solution to this is to add virtual keyword in base class function to get run
time polymorphism so that the call to the derived class can be made using the
base class pointer
#include <iostream>
class Base
{
153
OBJECT ORIENTED PROGRAMMING
public:
void disp()
{
cout<<"Base Class";
}
};
class Derived: public Base
{
public:
void disp()
{
cout<<"Derived Class";
}
};
int main()
{
Derived obj
Base *b = &Derived();
Obj->disp();
return 0;
}
When a derived class has more than one parents, an ambiguity arises in
multiple inheritance and in multipath inheritance.
The condition for ambiguity is that more than one parents class defines
methods with the same name, while a class derived from both base classes
has no function with this name.
The problem is how do derived class access the correct base class function.
the compiler can’t figure out which of the two functions is meant
154
Chapter 6: Inheritance and Polymorphism
Eg.
Class A and class B, both define a data member named int x and a data function
named getx(). Ambiguity is which copy of function or data member will class C
will receive?
Class A Class B
Int x; Int x;
getx() getx()
Class C
X???
getx??
A virtual function in C++ is a member function in the base class that is defined
again in derived class using the keyword virtual
The reason behind the virtual keyword is that it will make the compiler perform
dynamic linkage or late binding which involves binding of data during runtime.
A single pointer to the base class is created that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, it
155
OBJECT ORIENTED PROGRAMMING
always executes the base class function. To resolve this issue a 'virtual' keyword is
preceded at the normal declaration of the function.
When the function is made virtual, C++ determines which function is to be invoked
at the runtime based on the type of the object pointed by the base class pointer.
class base
{
public:
virtual void show()
{
cout<<"base func"<<endl;
}
};
class derived : public base
{
public :
void show()
{
cout<<"derived func"<<endl;
}
156
Chapter 6: Inheritance and Polymorphism
};
void main()
{
clrscr();
base *b;
derived d;
b=&d;
b->show();
getch();
}
Output
derived func
Constructor Destructor
A() B()
B() A()
#include<iostream>
class base
{
public:
157
OBJECT ORIENTED PROGRAMMING
base()
{
cout<<" constructor in base class"<<endl;
}
};
class derived:public base
{
public:
derived()
{
cout<<" constructor in derived class"<<endl;
}
};
int main()
{
derived d;
return 0;
}
All base class constructors are invoked first and than the derived class constructors
are invoked.
Order of calling the base class constructor depends upon the type the sequence of
inheritance of base class
Constructor Destructor
A() C()
B() B()
C() A()
158
Chapter 6: Inheritance and Polymorphism
C
#include<iostream>
class base
{
public:
base()
{
cout<<"constructor in base class"<<endl;
}
};
class base1
{
public:
base1()
{
cout<<"constructor in base class 1"<<endl;
}
};
class derived:public base, public base1
{
public:
derived()
{
cout<<”constructor in derived class"<<endl;
}
159
OBJECT ORIENTED PROGRAMMING
};
int main()
{
derived d;
return 0;
}
Base class constructor will be invoked first with the values of parameter after that
the derived class constructor will be get executed with the parameter value.
#include<iostream.h>
#include<conio.h>
class Base
{
int x;
public:
Base(int i)
{
x = i;
cout<< "Base Parameterized Constructor\n";
}
};
class Derived : public Base
{
int y;
public:
Derived(int j):Base(j)
{
y = j;
cout<< "Derived Parameterized Constructor\n";
160
Chapter 6: Inheritance and Polymorphism
}
};
int main()
{
Derived d(10) ;
getch();
return 0;
}
A derived class is derived from a base class with different access control or
modifiers.
Method Hiding takes place when the derived class has function with same
name as that of the function in base class, then the derived class function will
hide all base class function with same name even if the signatures are
different
https://www.geeksforgeeks.org/
161
OBJECT ORIENTED PROGRAMMING
6.11 Bibliography
162
UNIT 4
7
INHERITANCE AND POLYMORPHISM
Unit Structure
7.0 Objectives
7.1 Introduction
7.2 Polymorphism
7.7 Interfaces
7.10 Bibliography
7.0 Objective
163
OBJECT ORIENTED PROGRAMMING
7.1 Introduction
7.2 Polymorphism
During compile time, the compiler decides which function to address if there are
one or more functions with same name. Depending upon the number of arguments
present in the function, the compiler decided which function to call. Function
overloading implements compile time polymorphism. Compile time polymorphism
is fast in terms of execution time. It is also known as early binding.
Example :
# include<iostream.h>
# include<conio.h>
int area(int s);
int area(int l,int b);
float area(float r);
void main()
{
clrscr();
int a=10;
int b=20;
float c=1.2;
cout<<"area of a square "<<area(a);
cout<<"\narea of a rect "<<area(a,b);
cout<<"\n area of a circle "<<area(c);
getch();
}
int area(int s)
164
Chapter 7: Inheritance and Polymorphism
{
return(s*s);
}
int area(int l, int b)
{
return(l*b);
}
float area(float r)
{
return(3.14*r*r);
}
During run time polymorphism the decision about which function to be called is
taken during the runtime of the program. Function overriding implements runtime
polymorphism where in the base class and the child class consist of functions with
same name. Compiler decides at runtime whether the functions in the base class is
supposed to be called or the function with same name in child class is supposed to
be called. Run time polymorphism is slower in execution. It is also known as late
binding.
#include <iostream.h>
#include <conio.h>
class base
{
public:
virtual void show()
{
cout<<"base func"<<endl;
165
OBJECT ORIENTED PROGRAMMING
}
};
class derived : public base
{
public :
void show()
{
cout<<"derived func"<<endl;
}
void show1()
{
cout<<"show1 method implemented"<<endl;
}
};
void main()
{
clrscr();
base *b;
derived d;
b=&d;
b->show();
b->show1();
d.show();
d.show1();
getch();
}
166
Chapter 7: Inheritance and Polymorphism
Virtual functions appearto be calling a function of one class but in realityit is calling
a function of another class.
When base and derived classes consist of functions with same name, the function
in the base class is declared as virtual using the keyword virtual followed by its
declaration.
Concept behind the virtual function involves polymorphism and late binding.
The need to make the pointer of the base class to point and refer to the rest other
derived classes got resolved using virtual function.
Base class pointer pointing to derived class address used to get ignored by the
compiler and instead of displaying the content inside the derived class, the content
inside the base class function used to get executed every time. This was resolved
using the virtual keyword in the based class.
Example:
base *b;
b=&d;
b->display; // this display will refer the function of base class due to early
binding.
Program :
# include <iostream>
using namespace std;
class Base
{
public:
void display( ) {cout<< "\n Display base ";}
virtual void show( ) {cout; << "\n show base";}
};
class derived : public Base
{
public;
167
OBJECT ORIENTED PROGRAMMING
Virtual function cannot be static and can be accessed using object pointer
Pure Virtual Function don’t have any function definition and therefore also known
as ‘do nothing’ class.
The word pure is not a keyword.To convert a virtual class into pure virtual, ‘=0’ is
supposed to be added in the virtual class declaration
The pure virtual function don’t have any definition inside the base class that is why
equated with zero, but it also means that the function is supposed to defined in all
its derived classes.
168
Chapter 7: Inheritance and Polymorphism
class base
{
public:
virtual void show()
{
cout<<"base func"<<endl;
}
virtual void show1()=0; //pure virtual
};
class derived : public base
{
public :
void show()
{
cout<<"derived func"<<endl;
}
void show1()
{
cout<<"show1 method implemented"<<endl;
}
};
void main()
{
clrscr();
base *b;
derived d;
b=&d;
b->show();
b->show1();
d.show();
d.show1();
getch();
}
169
OBJECT ORIENTED PROGRAMMING
Using the pointer to the base class, the derived class objects can be deleted using
the virtual destructor
Base class pointer can store address of base class object as well as derived class
object
When base class pointer points to the base class object both constructor and
destructors are called.
But when base class pointer points to derived class object then constructors of both
base as well as derived classes are called but destructor of only derived class is
called
#include <iostream.h>
#include <conio.h>
class base
{
public:
base()
{
cout<<"base class constructor"<<endl;
}
~base()
{
cout<<"base class destructor"<<endl;
}
};
class derived : public base
{
public :
derived()
{
170
Chapter 7: Inheritance and Polymorphism
No object of the abstract class can be created but pointer of the abstract class can
be created
The usage of abstract class is to provide base class to other derived classes. All
common codes of derived classes are written inside the abstract class.
All pure virtual functions inside the abstract classes are supposed to be
implemented by all its derived classes or else they will become Abstract too
Eg: Base class database has a pure virtual function name getname(), this function
will be compulsorily get its definition in each derived classes as student, faculty
and librarian need to specify their name.
171
OBJECT ORIENTED PROGRAMMING
#include <iostream.h>
#include <conio.h>
class shape
{
public:
virtual void area()=0;
};
class rect : public shape
{
int a,b;
public:
void area()
{
cout<<"enter 2 no";
cin>>a>>b;
cout<<a*b<<endl;
}
};
class square : public shape
{
172
Chapter 7: Inheritance and Polymorphism
int a;
public:
void area()
{
cout<<"enter 1 no";
cin>>a;
cout<<a*a<<endl;
}
};
void main()
{
clrscr();
// shape o; // error as shape is an abstract class
rect r;
square s;
r.area();
s.area();
getch();
}
7.7 Interface
An abstract class in created by placing atleast one pure virtual function inside the
class.
173
OBJECT ORIENTED PROGRAMMING
Using the pointer to the base class, the derived class objects can be deleted
using the virtual destructor
https://www.geeksforgeeks.org/
7.11 Bibliography
174
UNIT 5
8
STREAMS
Unit Structure
8.1 Objectives
8.2 Files
8.9 Manipulators
8.11 Summary
8.1 Objectives
175
OBJECT ORIENTED PROGRAMMING
● To Understand other features of C++ that are related to files, including in-
memory text formatting, command-line arguments, overloading the insertion
and extraction operators, and sending data to the printer.
8.2 Files
A file constitutes a sequence of bytes on the disk where a group of related or similar
data is stored. File is created for permanent storage of data. A file is generally used
as real-life applications that contain a large amount of data.
The basic difference between text files and binary files is that in text files
various character translations are performed such as “\r+\f” is converted into
“\n”, whereas in binary files no such translations are performed.
176
Chapter 8: Streams
We first learn the function of different file-system in c++ before proceeding for
example
Name Function
fopen( ) Open a file.
fclose( ) Closes a file.
putc( ) Writes a character to a file.
fputc( ) Same asputc().
getc( ) Reads a character from a file.
fgetc( ) Same asgetc().
fgets( ) Reads a string from a file.
fputs( ) Writes a string to a file.
fseek( ) Seeks to a specified byte in a file.
ftell( ) Returns the current file position.
fprintf( ) Is to a file whatprintf()is to the console.
fscanf( ) Is to a file whatscanf()is to the console.
feof( ) Returns true if end-of-file is reached.
ferror( ) Returns true if an error has occurred.
rewind( ) Resets the file position indicator to the beginning of the file.
remove( ) Erases a file.
fflush( ) Flushes a file.
List.1 Commonly Used File-System Functions
In the tables below we will see the various steps and operations that can (or must)
be performed to use files in C++:
177
OBJECT ORIENTED PROGRAMMING
or or
ofstream out; ofstream out;
out.open(“myfile.txt”); out.open(“myfile.txt”, ios::binary);
● For Appending (adding text at the end of the existing file)
Text Files Binary Files
ofstream ofstream out
out(“myfile.txt”,ios::app); (“myfile.txt”,ios::app|ios::binary);
or or
ofstream out; ofstream out;
out.open(“myfile.txt”, ios::app); out.open(“myfile.txt”, ios::app |
ios::binary);
178
Chapter 8: Streams
#include<iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; // Creating object of fstream class
st.open("E:\samplefile.txt",ios::out); // Creating new file
if(!st) // Checking whether file exist
{
179
OBJECT ORIENTED PROGRAMMING
Example:Writing to a File
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; //Creating object of fstream class
st.open("E:\samplefile.txt",ios::out); // Creating new file
if(!st) //Checking whether file exist
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
st<<"Hello"; //Writing to file
st.close(); //Closing file
}
getch();
return 0;
}
180
Chapter 8: Streams
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; //Creating object of fstream class
st.open("E:\samplefile.txt",ios::in); // Creating new file
if(!st) //Checking whether file exist
{
cout<<"No such file";
}
else
{
char ch;
while (!st.eof())
{
st >>ch; //Reading from file
cout << ch; //Message Read from file
}
st.close(); //Closing file
}
getch();
return 0;
}
#include <iostream>
#include<conio>
#include <fstream>
using namespace std;
int main()
{
fstream st; //Creating object of fstream class
st.open("E:\samplefle.txt",ios::out); // Step 2: Creating new file
181
OBJECT ORIENTED PROGRAMMING
In stream class we have used the cin and cout stream objects. Different
streams are used to represent different varieties of data flow. e.g. ifstream
class constitutes data flow from input disk files.
The I/O system controls file operations which are very much similar to the
console input and output operations in C++ streams.
The stream that provides data to the program is called the input stream and
the one that receives data from the program is called output stream.
The input operation is responsible for the creation of an input stream and
linking it with the program and input file. Similarly, the output operation is
responsible for establishing an output stream with the necessary links with
the program and output file.
Input Stream reads the data from disk files and supplies to the program using
data input and receiving data from the output stream shown in the diagram.
182
Chapter 8: Streams
The I/O system contains a set of classes that defines the file handling
methods. These include ifstream, ofstream, and fstream.
These classes are derived from fstreambase and form the equivalent iostream
class.
These classes, designed to manage the disk files are declared in fstream class
and therefore this file is included in any program that uses these files.
1. The ios class: This class is responsible for providing all input and output
facilities to all other stream classes.
2. The istream class: This class is responsible for handling the input stream.
It provides several functions for handling chars, strings, and objects such as
to get, getline, read, ignore,
3. putback, etc.
4.
#include <iostream>
using namespace std;
183
OBJECT ORIENTED PROGRAMMING
int main()
{
char x;
// used to scan a single char
cin.get(x);
cout << x;
}
5. The ostream class: This class is responsible for handling output streams. It
provides several functions for handling chars, strings, and objects such as
write, put, etc.
#include <iostream>
using namespace std;
int main()
{
char x;
// used to scan a single char
cin.get(x);
// used to put a single char onto the screen.
cout.put(x);
}
6. The iostream: This class is responsible for handling both input and output
stream as both the istream class and istream class is inherited into it. It
provides the function of both istream class and istream class for handling
chars, strings, and objects such as to get, getline, read, ignore, putback, put,
write, etc.
#include <iostream>
using namespace std;
int main()
{
// this function display
// ncount character from array
cout.write(“iostreamclasses", 5); }
184
Chapter 8: Streams
Class Contents
filebuf Its purpose is to set the file buffers to read and write. Contains
Openprot constant used in the open() of file stream classes. Also
contain close()and open()as members.
fstreambase Provides operations common to file streams. Serves as a base for
fstream, ifstream and ofstream class. Contains open() and
close() functions.
ifstream Provides input operations. Contains open() with default input
mode. Inherits the functions get(), getline(), read(), seekg(),
tellg() functions from istream.
ofstream Provides output operations. Contains open() with default output
mode. Inherits put(), seekp(), tellp() and write() functions from
ostream.
fstream Provides support for simultaneous input and output operations.
Contains open with default input mode. Inherits all the functions
from istream and ostream classes through iostream.
These classes are derived directly/indirectly from the classes istream and ostream.
In the stream of c++, we are using these classes: cin is an object of class istream
and cout is an object of class ostream. The only difference is that we have to
associate these streams with physical files. Let's see an example:
Example:
185
OBJECT ORIENTED PROGRAMMING
Open a file
The first operation of stream/file is opening a file for operation, generally
performed on an object of one of these classes is to associate it to a real file.
filename is a string : the name of the file to be opened, and mode is an optional
parameter with a combination of the following flags:
All these flags can be combined using the bitwise operator OR (|). For
example, if we want to open the file example.bin in binary mode to add data
we could do it by the following call to member function open:
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Each of the open member functions of classes ofstream, ifstream and fstream
has a default mode that is used if the file is opened without a second
argument:
186
Chapter 8: Streams
In ifstream and ofstream classes, ios:: in and ios::out mode parameters are
automatically and respectively accepted, even if a mode that does not include
them is passed as a second argument to the open member function.
For the fstream class, the default value is applied if the function is called
without specifying any value for the mode parameter. If this function is called
with any value in that parameter the default mode is overridden by this class,
not combined in-stream class.
We need to check if a file stream was successful in opening a file or not, you
can do it by calling a member is_open. This open() function returns a Boolean
value of true in the case that to be sure the stream object is associated with
an open file or false otherwise:
if (myfile.is_open())
Closing a file
When we are finished with input and output operations on a file we need to close
it so that the operating system is notified and its resources have become free. For
that, we call the close () function.
myfile.close();
A file pointer is a pointer to a structure of type FILE, the FILE pointer allows us
to read the content of a file when we open the file in read-only mode. It
automatically points at the beginning of the file, allowing us to read the file from
the beginning. This pointer defines various things about the file, including its name,
status, and the current position of the file.
FILE *fp;
Opening a File
The fopen() function opens a stream for use and links a file with that stream. Then
it returns the file pointer associated with that file. Most often, the file is a disk file.
The fopen() function has this prototype:
187
OBJECT ORIENTED PROGRAMMING
Closing a File
The fclose() function closes a stream that was opened by a call to fopen() function.
This function writes any data remaining in the disk buffer to the file and does a
formal operating-system-level close on the file. Failure to close a stream invites all
kinds of trouble, including lost data, destroyed files, and possible intermittent errors
in your program. closing of a file also frees the file control block associated with
the stream, making it available for reuse. There is an operating-system limit to the
number of open files you may have at any one time, so you may have to close one
file before opening another.
Example:
#include <iostream>
int main()
{
cerr << "An error occured";
return 0;
}
188
Chapter 8: Streams
Example:
#include <iostream>
using namespace std;
int main()
{
clog << "An error occured";
return 0;
}
Random-access read and write operations using an I/O system with the help
of fseek(), which sets the file position indicator. Its prototype is shown here:
189
OBJECT ORIENTED PROGRAMMING
8.9 Manipulators
Manipulators are formatting instructions inserted directly into a stream.
It does not mean that we change the value of a variable, it only modifies the
I/O stream using insertion (<<) and extraction (>>) operators.
For example, if we want to print the hexadecimal value of 100 then we can
print it as:
Types of Manipulators
endl: It is defined in ostream. It is used to enter a new line and after entering a new
line it flushes the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in the string
sequence.
ends: It is also defined in ostream and it inserts a null character into the output
stream. It typically works with std::ostrstream, when the associated output buffer
needs to be null-terminated to be processed as a C string.
flush: It is also defined in ostream and it flushes the output stream i.e. it forces all
the output written on the screen or in the file. Without flush, the output would be
the same but may not appear in real-time.
Example:
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
190
Chapter 8: Streams
int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> std::ws, line);
return 0;
}
Output:
Programmer
only a test
abc
For Example, you can use following manipulators to set minimum width and fill
the space with any character you want:
191
OBJECT ORIENTED PROGRAMMING
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
192
Chapter 8: Streams
double A = 100;
double B = 2001.5251;
double C = 201455.2646;
// formatting
cout << hex << left << showbase << nouppercase;
// formatting
cout << setbase(10) << right << setw(15)
<< setfill('_') << showpos
<< fixed << setprecision(2);
// formatting
cout << scientific << uppercase
<< noshowpos << setprecision(9);
193
OBJECT ORIENTED PROGRAMMING
For example, if you have an object of class crawdad called cd1, you can
display it with the statement
cout << “\ncd1=” << cd1;
C++ can input and output the built-in data types using the stream extraction
operator >> and the stream insertion operator <<.
The stream insertion and stream extraction operators also can be overloaded
to perform input and output for user-defined types like an object.
The following example explains how the extraction operator >> and insertion
operator <<.
Example:
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output,
const Distance &D ) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
194
Chapter 8: Streams
int main()
{
Distance D1(11, 10), D2(5, 11), D3;
return 0;
}
Output:
· First Distance:F : 11 I : 10
· Second Distance:F : 5 I : 11
· Third Distance:F : 70 I : 10
8.11 Summary
● Files in C++ are associated with objects of various classes, typically ofstream
for output, ifstream for input, and fstream for both input and output.
● Member functions of these or base classes are used to perform I/O operations.
Such operators and functions as <<, put(), and write() are used for output,
while >>, get(), and read() are used for input.
195
OBJECT ORIENTED PROGRAMMING
● The read() and write() functions work in binary mode, so entire objects can
be saved to disk no matter what sort of data they contain.
● A check for error conditions should be made after each file operation. The
file object itself takes on a value of 0 if an error occurred. Also, several
member functions can be used to determine specific kinds of errors.
● The extraction operator >> and the insertion operator << can be overloaded
so that they work with programmer-defined data types. Memory can be
considered a stream, and data sent to it as if it were a file.
Reference Books:
Web References:
1. www.geeksforgeeks.org
2. www.javatpoint.com
196
UNIT 5
9
EXCEPTIONS
Unit Structure
9.1 Objectives
9.2 Error handling
9.3 Exceptions
9.4 Throwing and catching Exceptions
9.5 Custom Exceptions,
9.6 Built-in exceptions
9.7 Summary
9.8 Reference for further reading
9.9 Unit End Exercises
9.1 Objectives
Logical errors and syntactic errors are two most common types of error in a C++
programming language. The logic errors occur due to a poor understanding of the
problems in a particular area of subject. the syntax error arises due to poor
understanding of the programming language.
197
OBJECT ORIENTED PROGRAMMING
2. Run Time: After compilation when the program starts running from memory
the run time error is thrown.
9.3 Exceptions
In C++ Exceptions class identified an error while problems arise during compiling
and running a program. Exceptions are errors that occur at runtime. The errors are
caused by a wide variety of exceptional conditions, for example running out of
memory, unable to open a file, trying to initialize an object which is created by a
class, or using an out-of-bounds index to a vector.
In C++ Programming, objects are created using class, it means that they interact
with each other, during this interaction some problem occurs at this time program
detect an error in a try block and inform the exception handler to catch this
exception and display. try block throw and exception. Problem detected in the try
block will be caught in the catch block.
198
Chapter 9: Exceptions
Syntax:
try
{
//code1
} catch( ExceptionName e1one )
{
// catch1
} catch( ExceptionName e2two )
{
// catch2
} catch( ExceptionName enth )
{
// catch3
}
Example:
#include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
199
OBJECT ORIENTED PROGRAMMING
class Stack
{
private:
int st[MAX]; //array of integers
int top; //index of top of stack
public:
class Excp //exception class for Stack
{ //note: empty class body
};
Stack()
{
top = -1;
}
void push(int var)
{
if(top >= MAX-1) //if stack full,
throw Excp(); //throw exception
st[++top] = var; //put number on stack
}
int pop()
{
if(top < 0) //if stack empty,
throw Excp(); //throw exception
return st[top--]; //take number off stack
}
};
In C++ we can use more than one catch block with a try block. each catch must
catch a different type of exception.
Example, this program catches both integers and strings types in c++.
#include <iostream>
using namespace std;
void mulcatch(int testdigit)
200
Chapter 9: Exceptions
{
try
{
if(test)
throw testdigit;
else
throw "Value is zero";
}
catch(int i)
{
cout << "Caught Exception: " << i << '\n';
}
catch(const char *str)
{
cout << "Caught a string exception: ";
cout << str << '\n';
}
}
int main()
{
cout << "Start\n";
mulcatch(0);
mulcatch(1);
mulcatch(0);
mulcatch(2);
cout << "End of program";
return 0;
}
Output:
Start
Caught Exception : 0
Caught Exception : 1
Caught a string exception: Value is zero
Caught Exception : 2
End of program
201
OBJECT ORIENTED PROGRAMMING
● try block −. in this block logical code is kept for identifying a problem. The
keyword try is used to introduce a block of the statement which may generate
an exception. It's followed by one or more catch blocks.
// exceptions
#include<iostream>
using namespace std;
itry {
int size = 15;
if (size > 18) {
cout << "Access granted - you are fit.";
} else {
202
Chapter 9: Exceptions
throw (size);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 to fit.\n";
cout << "Size is: " << myNum;
}
● throwing an exception will end the method, it will affect the flow of code.
● If an exception occurred in the middle of the method, and the code below it
can't run.
● If that exception happened, then you would need to either enclose the whole
section in a try, catch block or throw an exception.
Throw exception;
Example:
#include <iostream>
using namespace std;
int main()
{
203
OBJECT ORIENTED PROGRAMMING
● Only two of the three statements are executed: the cout statement and the
throw.
● Control passes to the catch expression, and the try block is terminated.
● In the below example, we change the type in the catch statement to double
data type, the exception will not be caught and abnormal termination will
occur.
Example:
204
Chapter 9: Exceptions
{
cout << "we are Inside try block\n";
throw 100;
cout << "This not executed";
}
catch (double i)
{
cout << "Caught an exception: ";
cout << i << "\n";
}
cout << "End";
return 0;
}
Output:
Display of cout
we are Inside try block
terminate called after throwing an instance of ‘int’
● You can make your own exception class with help of std::exception.
● Custom exception class directly inherits from std::exception class .
#include <iostream>
#include <exception>
struct MyExcep : public std::exception
{
const char * what () const throw ()
{
return "C++ Exception class";
}
}
int main()
{
try
{
throw MyExcep();
}
205
OBJECT ORIENTED PROGRAMMING
catch (MyExcep& e)
{
std::cout << "MyExcep caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch (std::exception& e)
{
// Other errors if any
}
}
206
Chapter 9: Exceptions
Example 1:
#include<iostream>
using namespace std;
Class Problem
{
public:
Problem(const char* pStr=”There’s a problem”):pMessage(pStr)
{
}
const char* what() const
{
return pMessage;
}
private:
207
OBJECT ORIENTED PROGRAMMING
Example 2:
#include<iostream>
using namespace std;
int main()
{
for(int i=0;i<2;i++)
{
try
{
if(i==0)
throw Problem();
else
throw Problem(“No one seen the problems”);
}
catch(const Problem& t)
{
cout << endl << “Exception:” << t.what();
}
}
return 0;
}
9.7 Summary
208
Chapter 9: Exceptions
● The class member function finds the error and throws an exception, which is
caught by the program using the class, in exception-handler code following
the try block.
209
UNIT 6
10
CASTING, HEADER FILES &
LIBRARIES & NAMESPACES
Unit Structure
10.0 Objectives
10.1 Introduction
10.2 Casting
10.2.1 Static Casts
10.2.2 Const Casts
10.2.3 Dynamic Casts
10.2.4 Reinterpret Casts
10.3 Libraries and Header files
10.3.1 Creating Libraries
10.3.1.1 Creating Static Library
10.3.1.2 Creating Dynamic Library
10.3.2 Creating header files
10.4 Namespaces
10.4.1 Defining a Namespace
10.4.2 Accessing Namespace objects
10.4.3 The using directive
10.4.4 Unnamed Namespaces
10.4.5 Discontiguous Namespaces
10.4.6 Nested Namespaces
10.4.7 The std Namespace
10.5 Review Question
10.6 References
210
Chapter 10: Casting, Header Files & Libraries & Namespaces
10.0 Objectives
10.1 Introduction
This chapter deals with C++ concepts such as type conversion, header files
& libraries and namespaces.
Some of the concepts here are new to C++ and were not present in C
10.2 Casting
Example:
short a = 10;
int b = a;
211
OBJECT ORIENTED PROGRAMMING
Example:
double a = 10.5;
int b;
b = (int) a;
Output : 10
double a = 10.5;
int b;
b =static_cast<int> a;
cout<< b;
212
Chapter 10: Casting, Header Files & Libraries & Namespaces
Output : 10
Output:
c before call: 5
c after call: 125
● dynamic_cast may be used to cast one type of pointer into another or one type
of reference into another.
● The dynamic_cast performs a run-time cast. It verifies the validity of a cast.
● If the cast is invalid at the time dynamic_cast is executed, then the cast fails,
i.eIf the cast cannot be made, the cast fails and the expression evaluates to
null.
● The general form of dynamic_cast is shown here:
dynamic_cast<target-type> (expr)
● For example, consider two classes B and D, with D derived from B.
213
OBJECT ORIENTED PROGRAMMING
● Since a base pointer can always point to a derived object, a dynamic_cast can
always cast a D* pointer into a B* pointer. Consider the code below
Output: Cast OK
● Here, the cast from the base pointer bp to the derived pointer dp works
because bp is actually pointing to a Derived object. Thus, this fragment
displays Cast OK.
● In the next fragment, the cast fails because bp is pointing to a Base object and
it is illegal to cast a base object into a derived object.
214
Chapter 10: Casting, Header Files & Libraries & Namespaces
● Example
int main()
{
int* a= new int(78);
char* b = reinterpret_cast<char*>(a);
cout<< *a <<endl;
cout<< *b <<endl;
cout<< a <<endl;
cout<<ch<<endl;
return 0;
}
Output:
78
N
0x1c2ae70
N
215
OBJECT ORIENTED PROGRAMMING
● Dynamic Library
○ Also called as Shared library
○ A dynamic library generally has a “.so” extension
○ With a dynamic (shared) library, objects within the library are not
linked into the program’s executable file, but are loaded by the
compiler when required for execution.
○ Run time :These libraries are used at run-timei.e, the code is compiled
without using these libraries and these are linked at compile time to
resolve undefined references. It is then distributed to the application so
that application can load it at run time.
216
Chapter 10: Casting, Header Files & Libraries & Namespaces
217
OBJECT ORIENTED PROGRAMMING
// calcCube.cpp // cube.h
#include <iostream.h> intcalcCube(int d)
#include "cube.h” {
int main() return (d * d * d);
{ }
int d = 5;
cout<<"Cube of " <<d<< " = " <<calcCube(d);
return 0;
}
10.4 Namespaces
● Namespace is associated with scope. Scope defines and affects the visibility
of local & global variables.
● A namespace is a declaration that provides a scope to the identifiers inside it.
They are used to localize the names of identifiers to avoid name collisions.
● The members of a namespace belong to the same scope and can refer to each
other without special notation, whereas access from outside the namespace
requires explicit notation.
218
Chapter 10: Casting, Header Files & Libraries & Namespaces
namespace name {
// declarations
}
○ For example:
namespacemynewNamespace
{
int x, y;
}
○ In this case, the variables a and b are normal variables declared within a
namespace called mynewNamespace.
○ Example:
219
OBJECT ORIENTED PROGRAMMING
Output:
200
100
● Example
220
Chapter 10: Casting, Header Files & Libraries & Namespaces
namespace {
// declarations
}
Output:
25
25
221
OBJECT ORIENTED PROGRAMMING
Output:
10 20
200
222
Chapter 10: Casting, Header Files & Libraries & Namespaces
1. What is type casting? Explain the two main types of type conversion.
2. Explain the different types of casts with examples
3. Explain the difference between libraries and header files.
4. What are Libraries? What are its types?
5. Explain the process of creating static & dynamic libraries.
6. Explain with example creating and using a header file.
7. Explain the concept of a Namespace in detail
10.6 References
Books
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-
Hill
2. The C++ Programming Language, 4th Edition, Bjarne Stroustrup,
AddisonWesly
3. Absolute C++,4th Edition, Walter Savitch,Pearson Education
Web References
1. https://www.geeksforgeeks.org/difference-header-file-library/
2. https://docs.oracle.com/cd/E19205-01/819-5267/bkamn/index.html
3. https://www.bogotobogo.com/cplusplus/libraries.php
4. https://data-flair.training/blogs/header-files-in-c-cpp/
223
UNIT 6
11
GENERIC PROGRAMMING,
TEMPLATES & STL
Unit Structure
11.0 Objectives
11.1 Introduction
11.3 Templates
11.4 STL
11.4.1 Container
11.4.2 Algorithm
11.4.3 Iterator
11.4.4 Functions
11.6 References
11.0 Objectives
224
Chapter 11: Generic Programming, Templates & STL
11.1 Introduction
This approach allows us to write common functions or types that differ only
within the set of types on which they operate when used, thus
reducing duplication. Such software entities are referred to as generics.
Arrays and structs are often viewed as predefined generic types. Every usage
of an array or struct type instantiates a new base type, or reuses a previous
instantiated type. Element types such as Array and struct are parameterized
types, which are used to instantiate the corresponding generic type. All this
is often usually built-in in the compiler and therefore the syntax differs from
other generic constructs.
225
OBJECT ORIENTED PROGRAMMING
11.3 Templates
The templates declared for functions are called class templates. They perform
appropriate operations and rely on the data type of the arguments passed to
them.
These classes model a generic class which support similar operations for
various data types.
226
Chapter 11: Generic Programming, Templates & STL
public:
T functionName(T arg);
…
..
};
As shown above, a class template is created like any other class, except the
fact that it is preceded with the declaration Template <class T> which
specifies that what follows is a class template.T is the argument for template
and is a kindof placeholder for the data type used.
To create object of a class template, we have to define the data type within
a <> when creation. The general format is :
className<dataType> classObject;
Example:
o className<int> classObject;
o className<float> classObject;
o className<string> classObject;
#include <iostream>
using namespace std;
template <class T>
class IDOL
{
private:
T arg1, arg2;
public:
IDOL(T n1, T n2)
{
arg1 = n1;
arg2 = n2;
}
void displayResult()
{
227
OBJECT ORIENTED PROGRAMMING
cout << "Numbers are: " <<arg1<< " and " <<arg2<< "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
}
T add()
{
return arg1 + arg2;
}
};
int main()
{
IDOL<int> intAdd(5, 4);
IDOL<float> floatAdd(9.1, 4.5);
return 0;
}
Output
Explanation:
o The above program defines a class template IDOL. .
o The class contains two private members of type T: arg1 & arg2, and a
constructor to initalize the members.
o It contains public member functions to calculate the addition of the
numbers which returns the value of data type defined by the user & a
function displayResult() to display the output to the screen.
228
Chapter 11: Generic Programming, Templates & STL
o The main() function defines two different IDOL objects intAdd and
floatAdd created for data types: int and float respectively. Their values
are initialized using the constructor.
o Kindly note that we used<int> and <float> while creating the objects.
These tell the compiler of the data type used for the class creation.
o This creates a class definition for both int and float, which are then used
accordingly.
o Then, displayResult() of both objects is called which performs the
Addition operation and displays the output.
template<class T>
returntype functionname (argument of type T)
{
//body of function
//with Type T
//whenever appropriate
//……………
}
229
OBJECT ORIENTED PROGRAMMING
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &arg1, T &arg2)
{
T temp;
temp = arg1;
arg1 = arg2;
arg2 = temp;
}
int main()
{
int inum1 = 1, inum2 = 2;
float fnum1 = 1.1, fnum2 = 2.2;
char ch1 = 'a', ch2 = 'b';
cout << "Before passing data to function template.\n";
cout << "inum1 = " << inum1 << "\ninum2 = " << inum2;
cout << "\nfnum1 = " << fnum1 << "\nfnum2 = " << fnum2;
cout << "\nch1 = " << ch1 << "\nch2 = " << ch2;
Swap(inum1, inum2);
Swap(fnum1, fnum2);
230
Chapter 11: Generic Programming, Templates & STL
Swap(ch1, ch2);
cout << "\n\nAfter passing data to function template.\n";
cout << "inum1 = " << inum1 << "\ninum2 = " << inum2;
cout << "\nfnum1 = " << fnum1 << "\nfnum2 = " << fnum2;
cout << "\nch1 = " << ch1 << "\nch2 = " << ch2;
return 0;
}
Output
Explanation:
In the above program, a function template Swap() is defined that accepts two
arguments arg1 and arg2 of data type T.
Since the function does not return anything the return type is void
#include <iostream>
using namespace std;
// template function
template <class T>
T Greater(T arg1, T arg2)
{
return ((arg1 > arg2) ? arg1 : arg2);
231
OBJECT ORIENTED PROGRAMMING
}
int main()
{
int intval1, intval2;
float floatval1, floatval2;
char charval1, charval2;
cout << "Enter two integers:\n";
cin >> intval1 >> intval2;
cout << Greater(intval1, intval2) <<" is Greater." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> floatval1 >> floatval2;
cout << Greater(floatval1, floatval2) <<" is Greater." << endl;
cout << "\nEnter two characters:\n";
cin >> charval1 >> charval2;
cout << Greater(charval1, charval2) << " has Greater ASCII value.";
return 0;
}
Output
Enter two integers: Enter two floating-point Enter two characters:
15 numbers: m
12 21.14 N
15 is Greater. 120.21 m has Greater ASCII
120.21 is Greater. value.
Explanation:
o In the above program, a function template Greater() is defined that
accepts two arguments arg1 and arg2 of data type T.
o T signifies that argument can be of any data type.
o Greater() function returns the Greater among the two arguments using
a simple conditional operation.
232
Chapter 11: Generic Programming, Templates & STL
Using a comma-separated list we can use more than one generic data type
in the template statement, shown below
Example : Consider the following Example with two generic types in template
functions
int main()
#inlude <iostream> {
#include<string> display(2020, “JULY”);
using namespace std; display(14.20, “Y2K”);
template<class T1,class T2> return 0;
void display( T1 x, T2 y) }
{
cout<<x<<” “<<y<<”\n”;
}
Output
2020 JULY
14.20 Y2K
233
OBJECT ORIENTED PROGRAMMING
#include <iostream>
#include <string>
using namespace std;
template <class T>
void output(T arg)
{
cout<<”template output:” <<arg<< “\n”;
}
void output ( int arg)
{
cout<<”Explicit output: “<<arg<<”\n”;
}
int main()
{
output(121);
output(121.34);
output(‘IDOL’);
return 0;
}
Output
Explict output: 121
template output:121.34
template output: IDOL
11.4 STL
234
Chapter 11: Generic Programming, Templates & STL
The STL provides common programming data structures and functions such
as lists, arrays, stacks, etc. It is a generalized library with parameterized
components.
1. Containers
o A container is an object that actually stores data.
o It is a way data is organized in memory.
o The STL containers are implemented by template classes & can be
easily customized to hold different types of data.
2. Algorithms
o It is a procedure i.e used to process the data contained in the containers.
o STL includes many different algorithm to provide support to take such
as initializing, searching,popping, sorting, merging, copying.
o They are implemented by template functions.
3. Functions
o The STL includes classes that overload the function call operator.
Instances of these classes are usually known as function objects or
functors.
o Functors allow the working of the associated function to be customized
with the help of parameters to be passed.
4. Iterators
o It is an object like a pointer that points to an element in a container.
o We can use iterator to move through the contents of container.
o They are handles just like pointers we can increment or decrement
them.
o Algorithms in STL don’t work on containers, instead they work on
iterators, they manipulate the data pointed by the iterators.
11.4.1. Containers
o They are of three types
o Sequence Containers
o Associative Container
o Derived Container
235
OBJECT ORIENTED PROGRAMMING
o Sequence Containers
o They store elements in a linear sequence like a line.
o Each element is related to other elements by its position along the line.
o They expand themselves to allow insertion of elements & support a variety
of operations
o Following are some common containers:
o Vector –
It is a dynamic array.
It allows insertion & deletion & permits direct access to any element.
o List –
It is a bidirectional linear list.
It allows insertion & deletion anywhere.
o Dequeue –
It is a double ended queue.
It allows insertion & deletion at both ends.
o Associative Container
o Associative Containers are created to provide direct access to elements using
keys.
o They are of four types.
o Set
It is an associative container for storing unique sets.
Here, no duplicates are allowed.
o Multisets
Duplicate are allowed.
o Map
It is an associate container for storing unique key.
Each key is associated with one value.
236
Chapter 11: Generic Programming, Templates & STL
o Multimap
It is an associate container for storing key value pairs in which one key
may be associated with more than one value.
The main difference between a map & multimap is that, a map allows
only one key for a given value to be stored while multimap permits
multiple key.
o Derived Container or Container Adaptors
o STL provides 3 derived container, stack, queue, priority queue.
o They are also known as container adaptor.
o They can be created from different sequence container.
Stack – it is a LIFO list.
Queue – it is a FIFO list.
Priority queue – it is a queue where the 1st element out is always the
highest priority queue.
11.4.2 Algorithm
A number of useful, generic algorithms are usually provided by The Standard
Template Library (STL)to perform the most commonly used operations on
groups/sequences of elements.
binary search is used by Searching algorithms like lower bound and binary
search and usually require that the type of data must implement comparison
operator < or a custom comparator function.
237
OBJECT ORIENTED PROGRAMMING
11.4.3 Iterator
Iterators are the major feature that allows the generality of the STL.
238
Chapter 11: Generic Programming, Templates & STL
11.6 References
Books
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-
Hill
2. The C++ Programming Language, 4th Edition, Bjarne Stroustrup,
AddisonWesly
Web References
https://www.geeksforgeeks.org/
https://en.wikipedia.org/wiki/Generic_programming
239
UNIT 6
12
DATABASE PROGRAMMING
WITH MYSQL
Unit Structure
12.0 Objectives
12.1 Introduction
12.2 Different options for database connectivity
12.3 MySQL database connectivity with C++ using C library
12.3.1 Pre-requisites
12.3.2 Setting up Code Blocks &Testing connection
12.3.3 Connecting to MySQL database
12.3.4 Inserting and retrieving data
12.5 Review Question
12.6 References
12.0 Objectives
12.1 Introduction
This chapter demonstrates how C++ can be used to connect to the MySQL
database.
240
Chapter 12: Database Programming with MYSQL
The code is quite simple but the prerequisites need to be in place and the
library files need to be placed in the right location before the code can be
compiled. C++ being a High-Level Language makes it easy to start coding
with little understanding of underlying concepts.
All options are standard except for ODBC; its APIs are not standard.
Almost every database vendor provides a native client library to access its
database. The Client libraries are specific to the vendor; that means that the
API provided will work only with the vendors database who provided it.
Example: The client library and the API supplied by MySQL are quite
different from those of PostgreSQL.
The driver options for database programming of MySQL with C/C++ are:
o MySQL Client library
It is implemented in the libmysqlclient library.
It is a native C API library distributed with MySQL
The client API library is already installed withMySQL Server
installation.
o MySQL C/C++ Connector
The API is based on the JDBC4.0 API standard
It provides a separate connector for C and C++.
o ODBC
Stands for Open Database Connectivity
It was developed by Microsoft in the 90's.
it provides a vendor-neutral API to a access database system. All
database vendors provide an ODBC driver other than their native
support.
ODBC in general is a driver model, it contains the logic necessary
to convert a standard set of commands into calls that can be
understood by the underlying system. It can be seen as an
interface between the application and the database system to
facilitate the exchange of calls and responses among them.
241
OBJECT ORIENTED PROGRAMMING
We will attempt the MySQL database connectivity with C++ using C library
12.3.1 Pre-requisites
We need the following software, kindly download them as per the instructions
below:
1. Code Blocks
2. MySQL server (with client library)
3. Xampp
Code Blocks
o This will be our C++ IDE where we write our code
o We use the version with MinGW compiler included
o We have used codeblocks-20.03mingw-setup.exe(145 MB). Kindly
download 32 bit or 64 bit as per your system configuration, the
download link is http://www.codeblocks.org/downloads/26
Xampp
o Provides the integrated PHPmyAdmin interface and allows you
tomanage your MySQL database
o We have used xampp-windows-x64-7.4.8-0-VC15-installer.exe (155
MB). Kindly download 32 bit or 64 bit as per your system
configuration, the download link is
https://www.apachefriends.org/download.html
MySQL server (with client library)
o The core MySQL server
o It is installed with the MySQL Installer, mysql-installer-web-
community-8.0.21.0.exe. It installs the SQL Server along with C API.
The download link ishttps://dev.mysql.com/downloads/installer/
Installation and Configuration
Once the above mentioned software are downloaded install and configure them in
the following order:
1. XAMPP
The setup is straight forward just click next wherever necessary until
setup is finished
242
Chapter 12: Database Programming with MYSQL
2. CODE BLOCKS
The rest of the setup is straight forward just click next wherever
necessary until setup is finished
3. MYSQL Installer
243
OBJECT ORIENTED PROGRAMMING
244
Chapter 12: Database Programming with MYSQL
Under High Availability select Standalone MySQL Server and click Next
245
OBJECT ORIENTED PROGRAMMING
Under Type & Networking – Change Port number 3306 to 3307 as the same
is used by XAMPP and will conflict if not changed, click Next
Accounts & Roles – set password for the default root account. Here we set it
to Root@123. If you want you can add and optional user account by clicking
246
Chapter 12: Database Programming with MYSQL
Add User. We will create a user with name “test” & password “Test@123”
as shown below
Launch Code Blocks, select Create New Project, select Console Application
& Click Go, select C++ & click Next, Give a suitable title to the Project like
“test” & on next window click Finish.
Make sure you are able to successfully build & run the project.
247
OBJECT ORIENTED PROGRAMMING
If it does not automatically detect a path you will have to manually browse
for the folder MinGW in your Code Blocks Installation which is like this
C:\Program Files\CodeBlocks\MinGW
Next add the header files <mysql.h> and try to build & run. This will give an
error No such file or directory for mysql.h. To remove this error do the
following:
o Goto Project -> Build Options -> Linker Settings tab.
o Add the following two files
248
Chapter 12: Database Programming with MYSQL
Now, try to build & run. This time there should be no error.
249
OBJECT ORIENTED PROGRAMMING
Once you click Admin, the phpMyAdmin panel opens up in the default web
browser.
Create Database – Under the Databases Tab, type in the name of database to
be created and click Create. Here we create a database called “test”
Next, it will ask to create a table. Type the name “student” & no of columns
to “5” and click “Go” to create student table
Enter the values as shown below and click on the Save button in bottom
right corner
250
Chapter 12: Database Programming with MYSQL
Where:
conn = connection object,
127.0.0.1 = is the localhost loopback ipaddress
root = is the username of the mysql database
“” = no password is default for xamppphymyadmin interface
test = name of the database to be connected
251
OBJECT ORIENTED PROGRAMMING
#include <iostream>
#include <windows.h>
#include <mysql.h>
#include <string>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(0);
conn =
mysql_real_connect(conn,"127.0.0.1","root","","test",0,NULL,0);
if(conn)
cout<<"test database connected successfully "<<endl;
else
cout<<"connection problem: "<<mysql_error(conn)<<endl;
MYSQL_ROW row;
MYSQL_RES *res;
int qstate;
string Id, Name, Email, MobileNo, Course;
cout<<"enter Id : ";
cin>>Id ;
cout<<"enter Name : ";
cin>>Name;
cout<<"enter Email : ";
cin>>Email;
cout<<"enter MobileNo : ";
cin>>MobileNo;
cout<<"enter Course : ";
cin>>Course;
cout<<endl;
string query="insert into student(Id, Name, Email, MobileNo,
Course)
252
Chapter 12: Database Programming with MYSQL
values('"+Id+"','"+Name+"','"+Email+"','"+MobileNo+"','"+Course
+"')";
const char* q = query.c_str();
cout<<"query is: "<<q<<endl;
qstate = mysql_query(conn,q);
if(!qstate)
cout<<"Record Inserted Successfully..."<<endl;
else
cout<<"Query problem: "<<mysql_error(conn)<<endl;
qstate = mysql_query(conn,"select * from student");
if(!qstate)
{
res = mysql_store_result(conn);
while(row=mysql_fetch_row(res))
{
cout<<"Id : "<<row[0]<< " "
<<"Name : "<<row[1]<< " "
<<"Email : "<<row[2]<< " "
<<"MobileNo: "<<row[3]<< " "
<<"Course : "<<row[4]<< " "<<endl;
}
}
else
{
cout<<"query error: "<<mysql_error(conn)<<endl;
}
mysql_close(conn);
return 0;
}
253
OBJECT ORIENTED PROGRAMMING
1. What are the different ways of connecting MySQL database using C++?
2. What software are required for connecting MySQL database using C++?
3. List the 2 important library files needed for connecting MySQL database
using C++? Also mention their path.
254
Chapter 12: Database Programming with MYSQL
12.6 References
Books
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-
Hill
2. The C++ Programming Language, 4th Edition, Bjarne Stroustrup,
AddisonWesly
Web References
https://www.geeksforgeeks.org/
https://dev.mysql.com/doc/connector-cpp/1.1/en/connector-cpp-getting-
started-examples.html
255