Object Oriented Programming F.Y. MCA Semester I
Object Oriented Programming F.Y. MCA Semester I
Object Oriented Programming F.Y. MCA Semester I
Chapter 1
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 code need to check
1.7 Summary
1.8 Reference for further reading
1.9 Unit End Exercises
1.1 Objectives
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
Computers only understand the Binary language for example 0’s and 1’s (High
or Low), so these languages are the best way to give signals to the computer
directly.
Machine Code does not need any interpreter or compiler to convert language in
any form because the computer understands these signals directly.
For computers to understand the instructions written in Assembly language that
needs to be converted from Assembly language into equivalent Binary.
Languages like Java, .Net, Pascal, COBOL, C++, C, C# These languages come
under the high-level programming language category.
● Pre-processor Commands
● Functions
● Variables
● Statements & Expressions
● Comments
Example:
Header file #include<stdio.h>
int main()
Main() function
{
Variable
int a=10;
declaration
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.
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. }
class Car
//Data members
char name[20];
int speed;
int weight;
public:
//Functions
void brake(){
void slowDown(){
};
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>
class ParentClass {
//data member
public:
};
public:
};
int main(void) {
ChildClass obj;
Polymorphism
Examples of polymorphism are Function overloading and Operator overloading.
Polymorphism is a feature using which an object behaves differently in different
situations. In function overloading, we can have more than one function with the same
name but different numbers, type or sequence of arguments.
Example:
#include <iostream>
class Sum {
public:
int add(int num1,int num2){
};
int main(void) {
Sum obj;
cout<<obj.add(11, 22);
return 0;
Output:
60
33
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
Object-oriented Client-Server Systems provide the operating systems, networks, and
hardware, creating object-oriented Client-Server Internet (OCSI) applications.
2. 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.
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..
C C++
Function and operator overloading are not Function and operator overloading are
supported in C. supported by C++.
Namespace features are not present inside A namespace is used by C++, which
the C. avoids name collisions.
Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.
C provides malloc() and calloc() functions C++ provides a new operator for
for dynamic memory allocation, and free() memory allocation and delete operator
for memory deallocation. for memory deallocation.
scanf() and printf() functions are used for cin and cout are used for input/output
input/output in C. in C++.
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.
● 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.
Data Type Modifiers
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
float 4
double 8
long double 12
Note: Above values may vary from compiler to compiler. In the above example, we
have considered GCC 64 bit.
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
if a condition is fulfilled then only execute an instruction or block of
instructions. Its form is:
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 (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";
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:
break;
case 2:
break;
default:
● while
● do/while
● for
int main ()
int n;
cin >> n;
while (n>0) {
--n;
return 0;
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;
#include <iostream.h>
int main ()
return 0;
}
1.6.7 Operators and Expressions
An operator is a symbol or sign that tells the compiler to perform mathematical or logical
manipulations. C++ provide the following types of operators:
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Operato Description Example
r
#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
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Operato Description Example
r
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
Logical Operators
There are following logical operators supported by the C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Operato Description Example
r
#include <iostream>
using namespace std;
main()
{
int a = 50;
int b = 2;
int c ;
if(a && b)
{
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
Bitwise Operators
Bitwise operator works on bits and performs a bit-by-bit operation. The truth tables for
&, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit (A & B) will give 12 which is 0000
to the result if it exists in both 1100
operands.
<< Binary Left Shift Operator. The A << 2 will give 240 which is 1111
left operand's value is moved left 0000
by the number of bits specified by
the right operand.
>> Binary Right Shift Operator. The A >> 2 will give 15 which is 0000
left operand's value is moved right 1111
by the number of bits specified by
the right operand.
#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
Assignment Operators
There are following assignment operators supported by C++ language −
Operator Description 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
1.7 Summary
2.1Introduction
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.
#include<iostream.h>
Using namespace std;
int main()
{
cout<<”Welcome to the world of C++\n”;
return(0);
}
2.3Execution Flow
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.
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
2. Elements of the computer-user environment
a. Windows
b. Menus
c. Graphics objects (lines, rectangles, circles)
d. The mouse, keyboard, disk drives, printer
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
6. User-defined data types
a. Time
b. Angles
c. Complex numbers
d. Points on the plane
e. Physical Objects
7. Components in computer games
a. Cars in an auto race
b. Positions in a board game (chess, checkers)
c. Animals in an ecological simulation
d. Opponents and friends in adventure games
The match between programming objects and real world objects is the result of combining data
and functions.
#include <iostream>
using namespace std;
public:
void setdata(int d) //member function to set data
{
data = d;
}
void showdata() //member function to display data
{
cout << “Data is “<<data << endl; }
};
int main()
{
Demo s1, s2; //define two objects of class Demo
s1.setdata(10); //call member function to set data
s2.setdata(15);
s1.showdata(); //call member function to display data
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
Figure shows data & functions in a 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:
Data is 10 <---------- Object s1 displayed this
Data is 15 <---------- Object s2 displayed this
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:
public:
void setdata(int d) //member function to set
data
{ somedata = d; }
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.
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.
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.
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.
2.6 Access Modifiers
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.
What is the importance of using Access modifier in a program? In some cases, it makes
sense for objects of the derived class to access the public functions of the base class if they want
to perform a basic operation, and to access functions in the derived class to perform the more
specialized operations that the derived class provides.
In such cases public derivation is appropriate. In some situations, however, the derived class is
created as a way of completely modifying the operation of the base class, hiding or disguising its
original interface. The diagram below shows the accessibility of Private & public data or
functions in a class.
2.7Inline Functions
We all know that use of functions saves memory space but the whole process of calling a
function and jumping back to the next instruction in the program is time consuming. Hence
Inline functions came in picture. To save execution time in short functions, you may elect to put
the code in the function body directly inline with the code in the calling program. That is, each
time there’s a function call in the source file, the actual code from the function is inserted,
instead of a jump to the function.
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.
#include <iostream>
using namespace std;
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;
}
Output:
Value of x from my_fun: 50
Value of x from main function: 10
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
2.9Function with default arguments
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 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;
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():
The default argument follows an equal sign, which is placed directly after the type name. You
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.
2.10Function Overloading
An overloaded function appears to perform different activities depending on the kind of
data sent to it. It performs one operation on one kind of data but another operation on a different
kind. Let’s clarify with following example.
#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;
}
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.
Example:
#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
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
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Constructor called.
Constructor called.
Total objects: 2
By declaring a function member as static, you make it independent of any particular object of the
class. A static member function can be called even if no objects of the class exist and the static
functions are accessed using only the class name and the scope resolution operator ::.
A static member function can only access static data member, other static member functions and
any other functions from outside the class. Static member functions have a class scope and they
do not have access to the this pointer of the class. You could use a static member function to
determine whether some objects of the class have been created or not.
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;
int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Output:
Initial Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
2.15Bibliography
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-Hill
2. The C++ Programming Language, 4th Edition,BjarneStroustrup,AddisonWesly
3. Starting Out with C++ Early Objects,8th Edition,Tony Gaddis et al,Addison-Wesley
4. C++ How to Program,8th Edition,Deitel and Deitel, Prentice Hall
5. Practical C++ Programming,2nd Edition,Steve Quoaline,O’reilly Publication
6. Absolute C++,4th Edition, Walter Savitch,Pearson Education
3.2Introduction - Constructor
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
Example:
#include<iostream>
class construct {
public:
int a, b;
// 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
It is possible to pass arguments to constructors. Typically, these arguments help initialize an
object when it is created. To create a parameterized constructor, simply add parameters to it the
way you would to any other function. When you define the constructor’s body, use the
parameters to initialize the object.
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);
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.
Syntax:
Example:
#include<iostream>
class Point
{
private:
int x, y;
public:
Point (int x1, int y1) { x = x1; y = y1; }
// Copy constructor
Point (const Point &p2) {x = p2.x; y = p2.y; }
int main()
{
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
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;
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 point to parameterized constructor. So by keeping the same
name we can achieve constructor overloading.
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:
3.3Array - Introduction
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.
An array is a collection of items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array.
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.
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.
The items in a structure are accessed by name, while those in an array are accessed by an
index number. Using an index number to specify an item allows easy access to a large
number of items.
For example, if we say declare an array of 6 elements of integer datatype then it will look
this,
Following observations can be made from above array.
1. The size of Array= 6
2. First Index= 0
3. Last Index= 5
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
}
for(j=0; j<4; j++) //display 4 ages
cout << “You entered “ << age[j] << endl;
return 0;
}
Output:
Enter an age: 44
Enter an age: 16
Enter an age: 23
Enter an age: 68
You entered 44
You entered 16
You entered 23
You entered 68
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.
Stacks are one of the cornerstones of the architecture of the microprocessors used in most
modern computers.
Software stacks offer a useful storage device in certain programming situations.
Program:
#include <iostream>
class Stack
{
private:
enum { MAX = 10 }; //(non-standard syntax)
int st[MAX]; //stack: array of integers
int top; //number of top of stack
public:
Stack() //constructor
{ top = 0; }
int main()
{
Stack s1;
s1.push(11);
s1.push(22);
cout << “1: “ << s1.pop() << endl; //22
cout << “2: “ << s1.pop() << endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout << “3: “ << s1.pop() << endl; //66
cout << “4: “ << s1.pop() << endl; //55
cout << “5: “ << s1.pop() << endl; //44
cout << “6: “ << s1.pop() << endl; //33
return 0;
}
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;
cout << “ Enter inches: “; cin >> inches;
}
void showdist() const //display distance
{ cout << feet << “\’-” << inches << ‘\”’; }
};
int main()
{
Distance dist[100]; //array of distances
int n=0; //count the entries
char ans; //user response (‘y’ or ‘n’)
cout << endl;
do
{ //get distances from user
cout << “Enter distance number “ << n+1;
dist[n++].getdist(); //store distance in array
cout << “Enter another (y/n)?: “;
cin >> ans;
} while( ans != ‘n’ ); //quit if user types ‘n’
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.
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.
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.
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;
}
Output:
s3 = Man
s3 = Neither Man nor Beast
3.4Let us sum up
1. Classes includes objects, member functions, data members, access modifiers.
2. Object can be passed using value & reference.
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
3.6Bibliography
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-Hill
2. The C++ Programming Language, 4th Edition,BjarneStroustrup,AddisonWesly
3. Starting Out with C++ Early Objects,8th Edition,Tony Gaddis et al,Addison-Wesley
4. C++ How to Program,8th Edition,Deitel and Deitel, Prentice Hall
5. Practical C++ Programming,2nd Edition,Steve Quoaline,O’reilly Publication
6. Absolute C++,4th Edition, Walter Savitch,Pearson Education
OPERATOR OVERLOADING
Chapter 4
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:
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.
Overloading an operator simply means providing special syntax and semantics to an
existing operator. It enables an operator to exhibit more than one operation
simultaneously, as illustrated below:
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
This act of reinventing the effect of an operator is called operator overloading. Please
note that the original meaning and action of the operator however remains unchanged.
Only an additional meaning is added to it.
Similar to function overloading which allows different functions with different
argument list having the same name, an operator overloading can be reinvented to
perform additional tasks. Operator overloading is accomplished using a special function,
which can be a member function or friend function.
Syntax:
<return_type> operator <operator_being_overloaded>(<argument list>);
where, operator is the keyword and is preceded by the return_type of the operation.
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);
Let’s understand the overloading principle in more detail. In previous chapters we have
learn about the overloading principle which was applied to functions which we call as
function overloading. The same overloading principle is applied to an operator here. In
C++, most of operators can be extended to work with both built-in types as well as for
classes. However, there are few operators which cannot be overloaded which will see in
sometime. A programmer can apply his skill and discover a new operator to a class by
overloading the built-in operator function to perform some precise computation when the
operator is used on objects of that class. The question comes to a mind “Can operator
overloading be implemented for real world problems?” The answer to that is yes it
certainly possible to that, making it very easy to develop and deploy code that feels
natural. However in certain situations operator overloading, like any advanced C++
feature, makes the language slightly more complex. One must understand that every
operators tend to have very precise meaning, and most programmers don’t expect
operators to do a lot of versatile work, so overloading operators can be slightly more
confusing at times. Our intention in writing this book, is to keep it as simple as possible
so that the readers will be able to digest it fairly easily.
In C++, operator overloading can be achieve by implementing a function which can be:
4.2.1 Member Function
4.2.2 Non-Member Function
4.2.3 Friend Function
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.
public:
ABC(int abc) { m_abc = abc; }
int main()
{
ABC a1(6);
ABC a2 = a1 + 2;
std::cout << "I have " << a2.getABC() << " rupees.\n";
return 0;
}
Syntax:
friend return-type operator operator-symbol (var 1, var2)
{
//Statements;
}
#include<iostream>
using namespace std;
class UF
{
int x=10;
int y=20;
int z=30;
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;
}
Output:
Values of X, Y & Z
10
20
30
public:
// required constructors
ABC() {
f = 0;
in = 0;
}
ABC(int feet, int inches) {
f=feet;
inches=i;
}
// method to display distance
void displayABC() {
cout << "F: " << f << " I:" << in <<endl;
}
int main() {
ABC A1(11, 10), A2(-5, 11);
return 0;
}
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;
}
// 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;
// volume of box 3
vol = abc3.getVol();
cout << "Volume of ABC3 : " << vol <<endl;
return 0;
}
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;
}
int main() {
DistDemo DD1(11, 10), DD2(5, 11);
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.
Output:
a
a
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).
// Driver Method
int main()
{
int intArr[1024];
for (int x = 0, y = 0; x< 1024; x++) {
intArr[x] = y++;
}
// 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.
4.6 TYPE CONVERSION OPERATORS:
In C++, type conversion is a technique which allows one to convert the data from
one form to another.
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.
In C++, we can convert from one form to another as listed below
1. Automatic conversion
2. Primitive to Object
3. Object to Primitive
4. Object to Object
4.6.1 Automatic Conversion
This is pretty straight forward process and is often done implicitly.
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;
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.
In the above statement we will be storing float values in distance class and will show
it.
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();
}
Output:
Float to distance conversion
*********************************
Enter values in meter: 7
Converted values is: 22.96 feet and 275.59 inches
Program analysis:
In the above program, class Dist is created with two member variables: integer type
‘f’ and float type ‘in’.
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)
#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;
}
operator float() //overloaded casting operator {
float FIF=in/12;
FIF+=float(f);
return (FIF/MTF);
}
};
int main() {
int feet;
float inches;
cout <<"Enter distance in Feet and Inches.";
cout<<"\nFeet:";
cin>>feet;
cout<<"Inches:";
cin>>inches;
Dist dist(feet, inches);
float m=dist;
// This will call overloaded casting operator
cout<<"Converted Distance in Meters is: "<< m;
}
Output:
Enter the distance in Feet and Inches:
Feet: 22.96
Inches: 275.59
Converted Distance in Meters is: 7
Program analysis
In the above program, we have an overloaded casting operator which overloads float
type basic data type.
The logic is applied inside this operator definition, to merge feet and inches to get a
consolidate value in meters.
float FIF=in/12;
Similarly, we applied a formula which is to be casted the feet member variable to
float so that it can be added to FIF. Now FIF contain f + in.
Next, we need to divide this value by MTF variable which contains value 3.280833.
4.6.4 Object to Object
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 –
Y(object of class Y) = X(object of class X)
where ‘=’ has been overloaded for objects of class type ‘Y’.
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:
void operator =(Demo a)
{
y = a.get_str();
}
void display()
{
cout << y << endl;
}
};
int main()
{
// Creating object of class Class_type_one
Demo d;
Demo d1;
D1 = d;
d.display();
d1.display();
return 0;
}
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.
By overloading standard operators on a class, you can exploit the intuition of the
users of that class. This lets users program in the language of the problem
domain rather than in the language of the machine.
The ultimate goal is to reduce both the learning curve and the defect rate.
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.
The following operators cannot be overloaded
operator :: (scope),
operator .* (member object selector),
operator . (class object ...etc)
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.
Operator overloading can be implemented by
o Using member function
o Non-Member function
o Friend function
The keyword operator is used to overload an operator, and the resulting operator will
adopt the meaning supplied by the programmer.
Closely related to operator overloading is the issue of type conversion. Some
conversions take place between user defined types and basic types.
void show(){
cout<<"Complex Number: "<<i<<" + i"<<j<<endl;
}
void show_poss(){
cout<<"Your result after addition will be: "<<i<<" + i"<<j<<endl;
}
};
int main(int argc, char const *argv[])
{
complex c1(1,2);
complex c2(3,4);
c1 + c2;
return 0;
}
a) Complex Number: 4 + i6
b) Complex Number: 2 + i2
c) Error
d) Segmentation fault
8. Which operator should be overloaded in the following code to make the program error
free?
#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) +
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){}
c) bool operator==(Box b);
d) Box operator==();
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/
UNIT III
POINTERS IN C++
Chapter 5
Unit Structure:
5.0 Objective
5.1 Explicit and Mutable Pointers
5.2 Pointer and Address of Operator
5.3 Pointer to an Array
5.4 Array of Pointers
5.5 Pointer arithmetic
5.6 Pointer to a Constant
5.7 Constant Pointer
5.8 Pointer Declaration & Initialization
5.9 Types of Pointers
5.9.1 Void Pointer
5.9.2 Null Pointer
5.9.3 Dangling Pointer
5.10 Dynamic Memory Allocation
5.11 Advantages and Applications of pointers
5.12 Summary
5.13 Unit End Exercise
5.14 Further Readings
5.0 OBJECTIVE:
The diagram below depicts the values assigned in each of the variable after
execution of the code.
Example:
int (*ptr)[5];
In the above example, we have pointer variable(ptr) is pointer that points to an array of 5
integers. Please note that subscript have higher precedence than indirection, therefore, they
are enclosed in parentheses it is necessary to enclose the indirection operator and pointer
name inside parentheses. Here the type of ptr is ‘pointer to an array of 5 integers’.
Let us understand in more detail with the following code.
Program:
#include <iostream>
using namespace std;
int main()
{
// Pointer to an integer
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.
Let us understand by following diagram
In the above figure, whenever we dereferenced a pointer expression we get a value pointed to
by that pointer expression. Please note that whenever a pointer to an array is dereferenced, we
get the base address of the array to which it points.
5.4 ARRAY OF POINTERS:
When we have an array which consists of variables of pointer type, we have an
variable which is a pointer which address to some other element. This concept is
called as array of pointers.
Let us take an example and create an array of pointer holding 10 integer pointers;
then its declaration would look like:
int *ptr[10];
In the above statement, we have created an array of pointer named as ptr, and it
allocates 10 integer pointers in memory.
The element of an array of a pointer can also be initialized by assigning the address
of some other element. Let's us consider the following example
int x; // variable declaration.
ptr[1] = &x;
In the above code, we are assigning the address of 'x' variable to the second
element of an array 'ptr'.
Similarly, by using the concept of derefencing, we can derive the value of pointer
variable
1. *ptr[1];
1. Incrementing a Pointer
Let us understand this in more detail with the following program
#include <iostream>
using namespace std;
const int MAX = 5;
int main () {
int v[MAX] = {50, 100, 150, 200, 250};
int *ptr;
2. Decrementing a Pointer
In this case, similar contemplations apply to decrementing a pointer, which decreases its
value by the number of bytes of its data type as discussed below
Program:
#include <iostream>
using namespace std;
const int MAX = 5;
int main () {
int v[MAX] = {50, 100, 150, 200, 250};
int *ptr;
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.
2. No dereferencing is possible in case of void pointers.
Output:
A garbage Address
The above problem doesn’t appear (or p doesn’t become dangling) if x is a static
variable.
// The pointer pointing to local variable doesn't
// become dangling when local variable is static.
#include<stdio.h>
int *fun()
{
// x now has scope throughout the program
static int x = 5;
return &x;
}
int main()
{
int *p = fun();
fflush(stdin);
New Operator
In C++, dynamic memory allocation is done by using 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.
Examples:
delete a;
delete b;
Books
5. E Balagurusamy; Object-Oriented Programming with C++; Tata Mc Graw-Hill.
6. Herbert Schildt; The Complete Reference C++; Tata McGraw Hill.
7. Robert Lafore; Object-oriented Programming in Turbo C++; Galgotia.
8. Object Oriented Programming using C++-Lovely Professional University notes
Online links
6. http://www.mochima.com/tutorials/strings.html
7. http://www.exforsys.com/tutorials/c-plus-plus/operator-overloading-partii.html
8. http://publib.boulder.ibm.com/infocenter/comphelp/v8v101
index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm
9. http://www.cplusplus.com/doc/tutorial/pointers/
Unit – IV Inheritance and Polymorphism
Chapter 6
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.4Types 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.5Member hiding
6.6 Function overriding
6.7Multiple 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
6.0 Objectives
The objective of the chapter is as follow
To get familiar with concept of inheritance
To understand different types of inheritance
To understand the concept of member hiding, constructor inheritance
6.13 Introduction
Object Oriented Programming provides with an important characteristics known as
inheritance which leads to the reusability of code and reducing the work of writing
the same piece of code again
Inheritance are of different types which reflects different effect on its member
functions depending on its visibility mode
6.2 Inheritance concept
Inheritance is one of the important features supported by Object Oriented Programming.
It defines the hierarchical relationship between classes and supports the concepts of
division of code
It supports creating a derived class using the attributes and the methods of based class
Inheritance provides the reusability features which allows the code to be reusable. This
mechanism will allow the same class to be used by adding some additional features to it.
Resuability
Eg the base class is vehicle which is inherited by the train, car and flight
Vehicle
#include <iostream>
class base_classname
{
.... ... ....
};
protected:
int b;
public:
int c;
void get()
{
cout<<"enter 3 nos:";
cin>>a>>b>>c;
}
int get_pri()
{
return a;
}
};
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;
}
};
void main()
{
clrscr();
derived o;
o.show();
getch();
}
#include <iostream.h>
#include <conio.h>
//inheritance
/*
class derivedclass : access modifier baseclass
{
members of dc
};
*/
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;
}
};
void main()
{
clrscr();
derived o;
o.show();
getch();
}
6.4 Types of inheritance
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;
}
};
include <iostream>
class Animal
{
public:
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;
}
6.4.3 Multiple inheritance : inheritance in which the derived class inherits from more then one
base class
Syntax : class derived_classname : access_modifier base_classname1,
access_modifierbase_classname, ....
{
//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;
}
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();
}
6.4.4 Hierarchical inheritance: inheritance in which more than one derived class inherits from
the single base class
A B
#include <iostream>
using namespace std;
class Shape
{
public:
int l;
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;
int length,breadth,base,height;
cout<< "Enter the length and breadth of a rectangle: " ;
cin>>length>>breadth;
r.getdata(length,breadth);
6.4.5 Multipath inheritance: Inheritance in which a derived class is formed by two base classes
and these two base classes have one common base class is called multipath inheritance
A B
class emp
{
int age;
char name[10];
public:
int c;
void get()
{
cout<<"enter name & age:";
cin>>name>>age;
}
void show()
{
cout<<"name="<<name<<" age="<<age;
}
};
void getsal()
{
cout<<"enter sal";
cin>>sal;
}
void showsal()
{
cout<<" sal="<<sal;
}
};
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;
public:
void getscore()
{
cout<<"enter score";
cin>>score;
}
void showscore()
{
cout<<" rating="<<score;
}
};
void main()
{
clrscr();
performance p;
p.getscore();
f.show();
f.showsal();
p.showscore();
#include <iostream>
class Base
{
public:
void fun()
{
cout<<”void”<<endl;
}
Int main()
{
Derived d;
d.fun(‘a’);
d.Base::fun(2);
return(0);
}
Derived obj
Base *b = &Derived();
Obj->disp();
return 0;
}
6.7 Ambiguities in multiple inheritance and multipath inheritance and solution
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 name of the function alone is insufficient, since
the compiler can’t figure out which of the two functions is meant
Eg.
Lets say a class C inherits from both class A and class B
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??
class base
{
public:
virtual void show()
{
cout<<"base func"<<endl;
}
};
class derived : public base
{
public :
void show()
{
cout<<"derived func"<<endl;
}
};
void main()
{
clrscr();
base *b;
derived d;
b=&d;
b->show();
getch();
}
Output
derived func
B
#include<iostream>
class base
{
public:
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;
}
6.8.2 Multiple inheritance
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()
#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;
}
};
int main()
{
derived d;
return 0;
}
#include<iostream.h>
#include<conio.h>
class Base
{
int x;
public:
Base(int i)
{
x = i;
cout<< "Base Parameterized Constructor\n";
}
};
int main()
{
Derived d(10) ;
getch();
return 0;
}
6.11 Bibliography
The Complete Reference C, 4th EditionHerbertSehlidt,TataMcgraw Hill
The C++ Programming Language, 4th Edition,BjarneStroustrup,AddisonWesly
7.0 Objective
The objective of the chapter is as follow
To get familiar with concept of Polymorphism
To understand the difference between static and dynamic binding
To understand the concept of pure virtual function, virtual destructor and abstract
class
7.1 Introduction
Polymorphism allows to have multiple form. This characteristic of Object Oriented
Programming is explained in detail along with its types.
7.2 Polymorphism:
The word polymorphism means to have multiple forms. Polymorphism occurs in classes which
are related to each other by inheritance
Two types of polymorphism occur in C++:
7.2.1 Compile time Polymorphism or Static binding.
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>
void main()
{
clrscr();
int a=10;
int b=20;
float c=1.2;
int area(int s)
{
return(s*s);
}
float area(float r)
{
return(3.14*r*r);
}
#include <iostream.h>
#include <conio.h>
class base
{
public:
b=&d;
b->show();
b->show1();
d.show();
d.show1();
getch();
}
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;
void display( ) {cout<< "\n Display derived";}
void show( ) {cout<< "\ show derived";}
};
int main( )
{
Base B;
Derived D;
Base *bptr;
bptr = &D;
bptr->display( ); // calls Base version
bptr->show( ); // calls Derived version
return 0;
}
b=&d;
b->show();
b->show1();
d.show();
d.show1();
getch();
}
class base
{
public:
base()
{
cout<<"base class constructor"<<endl;
}
~base()
{
cout<<"base class destructor"<<endl;
}
};
};
void main()
{
clrscr();
base *b = new derived();
derived *d = new derived();
delete b;
delete d;
getch();
}
7.6 Abstract Class
A class that contains pure virtual function is called as Abstract Class
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.
#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
{
int a;
public:
void area()
{
cout<<"enter 1 no";
cin>>a;
cout<<a*a<<endl;
}
};
void main()
{
clrscr();
7.7 Interface
Behaviour or capabilities of a C++ class is described using the interface
Interface has no commitment for implementation of the described classes.
In C++ interfaces are implemented using the abstract classes.
An abstract class in created by placing atleast one pure virtual function inside the class.
7.8 Let us Sum Up
Polymorphism is of two types 1) Compile time Polymorphism or Static bindingand Run
time Polymorphism or Dynamic binding.
Virtual functions appearto be calling a function of one class but in realityit is calling a
function of another class
Using the pointer to the base class, the derived class objects can be deleted using the
virtual destructor
A class that contains pure virtual function is called as Abstract Class
7.11 Bibliography
The Complete Reference C, 4th EditionHerbertSehlidt,TataMcgraw Hill
The C++ Programming Language, 4th Edition,BjarneStroustrup,AddisonWesly
7.11 Unit End Exercise
Explain the concept of polymorphism
Write a program to demonstrate the use of virtual function
What are abstract classes?
Write short note on Virtual Destructor
UNIT 5: Streams
Chapter – 8
8.1 Objectives
8.2 Files
8.3 Text and Binary Files
8.4 Stream Classes
8.5 File IO using Stream classes
8.6 File pointers
8.7 Error Streams
8.8 Random File Access
8.9 Manipulators
8.10 Overloading Insertion and extraction operators
8.11 Summary
8.12 Reference for further reading
8.13 Unit End Exercises
8.1 Objectives
This chapter would make you understand the following concepts:
● To understand file and its types.
● To learn different C++ stream classes
● To understand of hierarchy of stream classes
● To learn how to perform file-related activities using C++
● 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.
Text files contain only textual data. However, unlike binary files, they have
fewer chances to become corrupted. While in a binary file may make it
unreadable because of a small error.
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.
Name Function
rewind( ) Resets the file position indicator to the beginning of the file.
In the tables below we will see the various steps and operations that can (or must) be
performed to use files in C++:
or or
or or
ifstream in ; ifstream in ;
out.close(); in.close();
Checking the end of the EOF() Used to check eof during the reading of the
file. file
Checking for the opened is_open() Checks if the file is opened or not, returns
file. ; true if the file is opened else
false
Several bytes already count() Returns count of the bytes read from the file
read.
Ignoring characters during ignore() Ignores n bytes from the file. (get pointer is
file read. positioned after n
character)
Checking the next peek() Checks the next available character, will not
character. increase the get pointer to the next
character.
Random access (only for seekg() In the case of binary files, random access is
binary files). performed using these functions. They either
seekp() give or set the position of getting and put
pointers on the particular location
tellg()
tellp()
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.close(); //Closing file
}
getch();
return 0;
Example:Writing to a File
#include <iostream>
#include<conio>
#include <fstream>
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;
#include <iostream>
#include<conio>
#include <fstream>
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>
int main()
{
fstream st; //Creating object of fstream class
st.open("E:\samplefle.txt",ios::out); // Step 2: Creating new file
st.close(); //Closing file
getch();
return 0;
}
8.4 Stream Classes
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, putback, etc.
#include <iostream>
int main()
{
char x;
cin.get(x);
cout << x;
3. 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>
int main()
char x;
cin.get(x);
cout.put(x);
4. 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>
int main()
cout.write(“iostreamclasses", 5); }
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.
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:
#include <iostream>
#include <fstream>
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile.close();
return 0;
}
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.
This method is known as opening a file.
The syntax for opening a file :
open (filename, mode);
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:
ios::app All output operations are performed at the end of the file, appending the
content to the current content of the file.
ios:: trunc If the file is opened for output operations and it already existed, its
previous content is deleted and replaced by the new one.
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:
ifstream ios::in
fstream ios::in | ios::out
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.
In file streams, input and output operations perform independently in binary
mode. Non-binary files are known as text files.
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())
{ /* ok, proceed with output */ }
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();
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:
FILE *fopen(const char *filename, const char *mode);
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.
The fclose() function has this prototype:
int fclose(FILE *fp);
A. Un-buffered standard error stream (cerr): In C++ cerr is the standard error
stream that is used to output or display the errors. This is an instance of the
ostream class. As cerr in C++ is unbuffered so it is used when one needs to
display the error message immediately. It does not have a buffer to store the
error message and display later.
Example:
#include <iostream>
int main()
{
cerr << "An error occured";
return 0;
#include <iostream>
int main()
return 0;
8.9 Manipulators
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>
int main()
string line;
return 0;
Output:
Programmer
only a test
abc
2. Manipulators with Arguments: Some of the manipulators are used with the
argument like setw (20), setfill ('*'), and many more. These all are defined in the
header file. If we want to use these manipulators then we must include this
header file in our program.
For Example, you can use following manipulators to set minimum width and fill
the space with any character you want:
setbase(val): It is used to set the numeric base value for numeric values.
hex: Read and write hexadecimal values for integers and it works the same as
the setbase(16).
dec: Read and write decimal values for integers i.e. setbase(10).
oct: Read and write octal values for integers i.e. setbase(10).
Example:
#include <iomanip>
#include <iostream>
int main()
double A = 100;
double B = 2001.5251;
double C = 201455.2646;
// formatting
// formatting
// formatting
Output:
0x64
_______+2001.53
2.014552646E+05
This is a powerful feature of C++. It lets you treat I/O for user-defined data types
in the same way as basic types like int and double.
For example, if you have an object of class crawdad called cd1, you can display
it with the statement
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.
Here, it is important to make the operator overloading function a friend of the
class because it would be called without creating an object.
The following example explains how the extraction operator >> and insertion
operator <<.
Example:
#include <iostream>
class Distance {
private:
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
feet = f;
inches = i;
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
friend istream &operator>>( istream &input, Distance &D ) {
return input;
};
int main()
return 0;
Output:
70
10
· First Distance:F : 11 I : 10
· Second Distance:F : 5 I : 11
· Third Distance:F : 70 I : 10
8.11 Summary
Reference Books:
1. Object Oriented Programming in C++,4th Edition,Robert Lafore,SAMS
Techmedia
2. The C++ Programming Language, 4th Edition,Bjarne Stroustrup, Addison
Wesley
Web References:
1. www.geeksforgeeks.org
2. www.javatpoint.com
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
This chapter would make you understand the following concepts:
● Exceptions provide a convenient, uniform way to handle errors that occur
within classes.
● To learn different kinds of exceptions.
● To learn how to prevent Exceptions provide a convenient, uniform way to
handle errors that occur within classes.
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.
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.
Fig.1 The exception mechanism
Syntax:
try
//code1
// catch1
// catch2
} catch( ExceptionName enth )
// catch3
Example:
#include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
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)
{
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
● 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>
itry {
} else {
throw (size);
Example:
#include <iostream>
int main()
try
catch (int i)
{ // catch an error
return 0;
Output:
Process End
● 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:
#include <iostream>
int main()
try
throw 100;
catch (double i)
return 0;
}
Output:
Display of cout
● 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();
}
catch (MyExcep& e)
{
std::cout << "MyExcep caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch (std::exception& e)
{
// Other errors if any
}
}
Example 1:
Throw a custom exception object-1
#include<iostream>
Class Problem
{
public:
Problem(const char* pStr=”There’s a problem”):pMessage(pStr)
{
}
const char* what() const
{
return pMessage;
}
private:
const char* pMessage;
};
Example 2:
Throw a custom exception object-2
#include<iostream>
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
Unit Structure
10.0 Objectives
10.1 Introduction
10.2 Casting
10.4 Namespaces
10.6 References
10.0 Objectives
10.1 Introduction
This chapter deals with C++ concepts such as type conversion, header
files & libraries and namespaces.
These are considered to be some advanced concepts.
Some of the concepts here are new to C++ and were not present in C
10.2Casting
● The concept of casting (or Type Casting in general) is related to (data)type
conversion. Type conversion is converting an expression of one type into another
type. Example converting a float type expression to integer type.
o Implicit Conversion
o Explicit Conversion
● Implicit Conversion – This type conversion is carried out by the C++ compiler
automatically.
Example:
short a = 10;
int b = a;
● Here, variable a is declared to be a short integer.
o dynamic_cast
o const_cast,
o reinterpret_cast, and
o static_cast.
● The traditional C-style cast : The casting is performed by putting the desired type
in parenthesis to the left of the variable we want to cast.
Example:
double a = 10.5;
int b;
b = (int) a;
Output : 10
● It can be used for any standard conversion. No run-time checks are performed.
double a = 10.5;
int b;
b =static_cast<int> a;
cout<< b;
Output : 10
Output:
c before call: 5
c after call: 125
dynamic_cast<target-type> (expr)
● 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.
● A dynamic_cast can cast a B* pointer into a D* pointer only if the object being
pointed to actually is a D object.
● In general, dynamic_cast will succeed if the pointer (or reference) being cast is a
pointer (or reference) to either an object of the target type or an object derived
from the target type. Otherwise, the cast will fail.
● If the cast fails, then dynamic_cast evaluates to null if the cast involves pointers.
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
● Header Files
○ They tell the compiler how to call some functionality, they contain the
function prototypes.
○ Example: GRAPHICS.H
● Static
● Shared or Dynamic
● Static Library
○ With a static library, its objects are generally contained in the object code
linked with an end-users application, and then becomes part of that
executable.
○ Compile time - These libraries are used at compile time meaning the
library should be present in the correct location when the user wants to
compile the C++ program.
● Dynamic Library
○ 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.
10.3.1 Creating Libraries
We will use the following codes to work with libraries.
// calc.cpp // main.cpp
intcalcCube(int);
o “-shared” creates a shared object libcalc.so which can then be linked with
other objects to form an executable.
// calcCube.cpp // cube.h
10.4 Namespaces
● Namespace is associated with scope. Scope defines and affects the visibility of
local & global variables.
● 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.
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.
int main()
{
// Local variable
int a = 200;
cout<<a; // outputs value local variable
return 0;
}
Output:
200
100
10.4.3 The using directive
● Frequent references to members of a namespace by having to specify the scope
resolution operator makes programming a tedious job.
○ using name::member;
● Example
namespace {
// declarations
● Example
● This is the reason why most of the programs in C++ include the following
statement using namespace std;
● This causes the std namespace to be the current namespace giving direct
access to the names the functions and classes defined without having to use
std:: everytime.
● Example : consider the following example using and without using std
namespace
// using namespace std // without using namespace std
return 0; return 0;
} }
10.6 References
Books
1. The Complete Reference-C++,4th Edition. Herbert Schildt,Tata McGraw-Hill
2. The C++ Programming Language, 4th Edition,BjarneStroustrup,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/
Unit 6 – Generic Programming, Templates & STL
Chapter 11
Unit Structure
11.0 Objectives
11.1 Introduction
11.3 Templates
11.4STL
11.4.1 Container
11.4.2 Algorithm
11.4.3 Iterator
11.4.4 Functions
11.6 References
11.0 Objectives
The objectives of this chapter are to:
Explain the concepts of Generic Programming
Explain Templates & associated concepts
Explain the concept of STL
11.1 Introduction
In this chapter we continuing our journey in the advanced concepts in C++
This chapter deals with C++ concepts of Generic Programming &
Templates.
Templates are one of C++'s most sophisticated and high-powered
features. Using templates we will create generic functions and classes.
11.2 Generic Programming
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.
void displayResult()
{
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 class contains two private members of type T: arg1 & arg2, and a
constructor to initalize the members.
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.
A function that successfully works for every C++ data type is known as a generic
function.
Arguments used as generic data types In templates and they can handle a
variety of data types.
Templates are a way to help the programmer to declare a group of functions and/
or classes. Templates when they are used with functions they are called normally
called function templates.
A function template is similar to a normal function, but only differ in one way. but,
While a single normal function can only work with one set of declared data types,
a single function template can work with variety of data types at same time.
Normally, to perform identical operations on two or more types of data, we use
function overloading to create two functions with the required function
declaration.
However, a better approach would be to use function templates because we can
perform the same task writing less and maintainable code.
The general form of a declaring function template is:
template<class T>
returntype functionname (argument of type T)
{
//body of function
//with Type T
//whenever appropriate
//……………
}
#include <iostream>
using namespace std;
int main()
{
int inum1 = 1, inum2 = 2;
float fnum1 = 1.1, fnum2 = 2.2;
char ch1 = 'a', ch2 = 'b';
Swap(inum1, inum2);
Swap(fnum1, fnum2);
Swap(ch1, ch2);
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);
}
int main()
{
int intval1, intval2;
float floatval1, floatval2;
char charval1, charval2;
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 Greater() function returns the Greater among the two arguments using a
simple conditional operation.
Output
2020 JULY
14.20 Y2K
#include <iostream>
#include <string>
using namespace std;
template <class T>
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
Itis a powerful set of C++ template classes that provide general-purpose classes
and functions with templates that implement most of commonly used data
structures & algorithms like vectors, lists, queues, and stacks.
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 The STL containers are implemented by template classes & can be easily
customized to hold different types of data.
2. Algorithms
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.
4. Iterators
o They are handles just like pointers we can increment or decrement them.
11.4.1. Containers
o They are of three types
o Sequence Containers
o Associative Container
o Derived Container
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.
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
11.4.3 Iterator
Iterators are normally used to point to STL containers. It is possible for an
algorithm to manipulate different types of data structures/Containers using
Iterators.
The five different types of iterators implemented by STLare:
1. Input iterators - that can only be used to read a sequence of values.
2. Output iterators - that can only be used to write a sequence of values.
3. Forward iterators - that can be read, written to, and move forward.
4. Bidirectional iterators - these are similar to forward iterators, but they can
also move back.
5. Random access iterators– these can move freely or randomly any number
of steps in a given operation.
We can define bidirectional iterators to behave similar to random access
iterators, since moving forward by ten steps can be done by simply moving
forward one step at a time for a total of ten times.
Distinct random-access iterators offer efficiency advantages. For example, a
vector may have a random-access iterator, but a list only has a bidirectional
iterator.
Iterators are the major feature that allows the generality of the STL.
For example, an algorithm that reverses a string can be implemented using
bidirectional iterators, later this same implementation can be used for lists,
vectors and deques.
User-created containers usually have to provide an iterator that implements at
least one of the available iterator interfaces, and then all the algorithms provided
in the STL can be used on the container.
This generality can prove costly at times.
For example, when performing a search on an associative container like a map
or set, it will be slower if iterators rather than by calling member functions offered
by the container itself. This is because the methods ofan associative
containercan take advantage of knowledge of the internal structure, which is not
transparent to algorithms using iterators.
Books
Web References
https://www.geeksforgeeks.org/
https://en.wikipedia.org/wiki/Generic_programming
Unit – 6 Database Programming with MySQL
Chapter 12
Unit Structure
12.0 Objectives
12.1 Introduction
12.3.1 Pre-requisites
12.6 References
12.0 Objectives
12.1 Introduction
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
3. Xampp
Code Blocks
Xampp
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
2. CODE BLOCKS
3. MYSQL Installer
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 Add User. We will create a user with name “test” &
password “Test@123” as shown below
Make sure you are able to successfully build & run the project.
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:
1. C:\Windows\System32
2. Your project folder where you can see *.cpp and *.cbp file
3. Your project folders debug directory - project path>\bin\debug\
Now, try to build & run. This time there should be no error.
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
int main()
{
MYSQL* conn; // Create Connection Object
conn = mysql_init(0); // Initialize Connection
conn = mysql_real_connect(conn,"127.0.0.1","root","","test",0,NULL,0);
if(conn)
cout<<"testdatabseconnected successfully "<<endl;
else
cout<<"connection problem: "<<mysql_error(conn)<<endl;
Where:
o Next, we will add the code to insert values in the database table we created
o We will take values from user and then display the same on the screen every time
a row is inserted
#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)
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;
}
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.
4. Create a database “IDOL” using phpMyAdmin interface, create a table called
“MCASEM1” with columns, data types shown below. Write a program in C++ to
connect to this database and Insert values as shown and display the value after
every insert.
1 MCA SCIENCE 3
2 MSCIT SCIENCE 2
3 BSCIT SCIENCE 2
4 MSCCS SCIENCE 2
5 BSCCS SCIENCE 3
12.6 References
Books
Web References
https://www.geeksforgeeks.org/
https://dev.mysql.com/doc/connector-cpp/1.1/en/connector-cpp-
getting-started-examples.html