0% found this document useful (0 votes)
47 views162 pages

Oops Notes

Object-oriented programming (OOP) is a programming paradigm that uses 'objects' to encapsulate data and methods, allowing for interaction between objects. Key concepts include encapsulation, inheritance, polymorphism, and abstraction, which enhance code reusability, security, and maintainability. OOP is widely used in various programming languages like Java, C++, and Python, and is applicable in areas such as client-server systems and object-oriented databases.

Uploaded by

pidame8353
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views162 pages

Oops Notes

Object-oriented programming (OOP) is a programming paradigm that uses 'objects' to encapsulate data and methods, allowing for interaction between objects. Key concepts include encapsulation, inheritance, polymorphism, and abstraction, which enhance code reusability, security, and maintainability. OOP is widely used in various programming languages like Java, C++, and Python, and is applicable in areas such as client-server systems and object-oriented databases.

Uploaded by

pidame8353
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

OBJECT

ORIENTED
PROGRAMMING
UNIT- 1

2
INTRODUCTION (OOP’s) :-
• Object-oriented programming (OOP) is a programming paradigm
based on the concept of "objects", which can contain data, in the form
of fields (often known as attributes or properties), and code, in the
form of procedures (often known as methods). A feature of objects is an
object's procedures that can access and often modify the data fields
of the object with which they are associated (objects have a notion of
"this" or "self").

• In OOP, computer programs are designed by making them out of objects


that interact with one another. OOP languages are diverse, but the most
popular ones are class-based, meaning that objects are instances of
classes, which also determine their types.

• Many of the most widely used programming languages (such as C++,


Java, Python, etc.) are multi-paradigm and they support object-oriented
programming to a greater or lesser degree, typically in combination
with imperative, procedural programming.

• Significant object-oriented language include Significant object-oriented


Languages include Java, C++, C#, Python, R, PHP, JavaScript,
Ruby, Perl, Objective-C, Dart, Swift, Scala, Kotlin, Common Lisp,
MATLAB, and Smalltalk.

3
DEFINATION :-

• Object-oriented Programming (OOP) refers to a type of computer programming


(software design) in which programmers define the data type of a data structure,
and also the types of operations (functions) that can be applied to the data
structure.

• In this way, the data structure becomes an object that includes both data and
functions. In addition, programmers can create relationships between one object
and another. For example, objects can inherit characteristics from other objects.

1. PROBLEMS WITH PROCEDURE ORIENTED


PROGRAMMING TECHNIQUE

• What is Procedure Oriented Programming (POP)?

Procedure oriented programming is a set of functions. In this program C


language is used. To perform any particular task, set of function are
compulsory. For example, a program may involve collecting data from user,
performing some kind of calculation on that data and printing the data on
screen when is requested. Calculating, reading or printing can be written in a
program with the help of different functions on different tasks.

4
 The problem with procedure oriented programming are :-

• The program code is harder to write when Procedural Programming is


employed
• The Procedural code is often not reusable, which may pose the need to
recreate the code if is needed to use in another application
• Difficult to relate with real-world objects
• The importance is given to the operation rather than the data, which might
pose issues in some data-sensitive cases
• The data is exposed to the whole program, making it not so much security
friendly

1. CONCEPTS OF OOP’S ( OBJECT ORIENTED


PROGRAMMING) :-

5
 Polymorphism :- The word polymorphism means having many forms.
In simple words, we can define polymorphism as the ability of a message to be
displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The
behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading:-
• Operator Overloading: The process of making an operator to exhibit
different behaviours in different instances is known as operator overloading.

• Function Overloading: Function overloading is using a single function


name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.

Example: Suppose we have to write a function to add some integers,


sometimes there are 2 integers, sometimes there are 3 integers. We can write
the Addition Method with the same name having different parameters , the
concerned method will be called according to parameters.

6
 Class: - The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.

Example: - Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the
class and wheels, speed limits, mileage are their properties.
• A Class is a user-defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions define the properties and behaviour of the
objects in a Class.
• In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can apply brakes, increase speed etc.

 Object: - An Object is an identifiable entity with some characteristics and


behavior. An Object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.
class person
{
char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1; // p1 is a
object
}

Object take up space in memory and have an associated address like a record
in Pascal or structure or union in C.

7
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can
interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and type of response returned
by the objects.
 Encapsulation: - Encapsulation is defined as wrapping up of data and
information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the functions that
manipulate them.

Encapsulation also leads to data abstraction or hiding. As using encapsulation


also hides the data. In the above example, the data of any of the section like
sales, finance or accounts are hidden from any other section.

 Abstraction: - Data abstraction is one of the most essential and


important features of object-oriented programming in C++. Abstraction
means displaying only essential information and hiding the details. Data
abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Abstraction are used in two cases :-
• Abstraction using Classes: We can implement Abstraction in C++ using
classes. The class helps us to group data members and member functions
using available access specifies. A Class can decide which data member
will be visible to the outside world and which is not.

8
• Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow () method present in math.
header file. Whenever we need to calculate the power of a number, we
simply call the function pow () present in the math. Headers file and pass
the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.

 Inheritance:-The capability of a class to derive properties and


characteristics from another class is called Inheritance. Inheritance is one of
the most important features of Object-Oriented Programming.

• Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.

• Super Class: The class whose properties are inherited by sub class is
called Base Class or Super class.

• Reusability: Inheritance supports the concept of “reusability”, i.e. when we


want to create a new class and there is already a class that includes some
of the code that we want, we can derive our new class from the existing
class. By doing this, we are reusing the fields and methods of the existing
class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

9
 Dynamic Binding: In dynamic binding, the code to be executed in
response to function call is decided at runtime. C++ has virtual functions to
support this.

 Message passing: Objects communicate with one another by sending and


receiving information to each other. A message for an object is a request for
execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function and the
information to be sent.

2. CHARACTERISTICS OF OOP’s :-

The main characteristics of OOP’s:-

 Data Hiding: This concept is the main heart of Object-oriented


programming. The data is hidden inside the class by declaring it as private
inside the class. When data or functions are defined as private it can be
accessed only by the class in which it is defined. When data or functions are
defined as public then it can be accessed anywhere outside the class.
Object-Oriented programming gives importance to protecting data in any
system. This is done by declaring data as private and making it accessible
only to the class in which it is defined. This concept is called data hiding. But
one can keep member functions as public.

10
 Encapsulation: The technical term for combining data and functions
together as a bundle is an encapsulation.

 Inheritance: As the name suggests is the concept of inheriting or


deriving properties of an exiting class to get a new class or classes. In
other words, we may have common features or characteristics that may
be needed by a number of classes. So those features can be placed in a
common tree class called base class and the other classes which have
these characteristics can take the tree class and define only the new
things that they have on their own in their classes. These classes are
called the derived classes. The main advantage of using this concept of
inheritance in Object-oriented programming is it helps in reducing the
code size since the common characteristic is placed separately called
base class and it is just referred to in the derived class. This provides the
users the important usage of terminology called reusability

 Reusability: This usage is achieved by the above-explained


terminology called inheritance. Reusability is nothing but re-usage of the
structure without changing the existing one but adding new features or
characteristics to it. It is very much needed for any programmers in
different situations. Reusability gives the following advantages to users It
helps in reducing the code size since classes can be just derived from
existing one and one need to add only the new features and it helps
users to save their time. For instance, if there is a class defined to draw
different graphical figures says there is a user who wants to draw a
graphical figure and also add the features of adding color to the graphical
figure. In this scenario instead of defining a class to draw a graphical
figure and coloring it what the user can do is make use of the existing
class for drawing graphical figure by deriving the class and add a new
feature to the derived class namely add the feature of adding colors to
the graphical figure.

 Polymorphism and Overloading: Poly refers too many. So


Polymorphism as the name suggests is a certain item appearing in
different forms or ways. That is making a function or operator to act in
different forms depending on the place they are present is called
Polymorphism. Overloading is a kind of polymorphism. In other words
say for instance we know that +, – operate on integer data type and is
used to perform arithmetic additions and subtractions. But operator
overloading is one in which we define new operations to these operators

11
and make them operate on different data types in other words over
loading the existing functionality with the new one. This is a very
important feature of object-oriented programming methodology which
extended the handling of data type and operations.

 Abstraction: It is one of the principles of object-oriented programming.


It is used to display only the necessary and essential features of an
object to the outside world.

 Classes: These contain data and functions bundled together under a


unit. In other words class is a collection of similar objects. When we
define a class it just creates a template or Skelton. So no memory is
created when class is created. Memory is occupied only by the object.

3. ADVANTAGES AND APPLICATION OF OOP’S :-

ADVANTAGES OR BENEFITS OF OOP’S ARE :-


a. Re-usability:-
It means reusing some facilities rather than building it again and again. This
is done with the use of a class. We can use it ‘n’ number of times as per our
need.

b. Data Redundancy :-
This is a condition created at the place of data storage (you can say
Database where the same piece of data is held in two separate places. So
the data redundancy is one of the greatest advantages of OOP. If a user
wants a similar functionality in multiple classes he/she can go ahead by
writing common class definitions for the similar functionalities and inherit
them

c. Code Maintenance:-
This feature is more of a necessity for any programming languages, it helps
users from doing re-work in many ways. It is always easy and time-saving to
maintain and modify the existing codes with incorporating new changes into
it.

12
d. Security :-
With the use of data hiding and abstraction mechanism, we are filtering out
limited data to exposure which means we are maintaining security and
providing necessary data to view.

e. Design Benefits:-
If you are practicing on OOPs the design benefit a user will get is in terms of
designing and fixing things easily and eliminating the risks (if any). Here the
Object Oriented Programs forces the designers to have a longer and
extensive design phase, which results in better designs and fewer flaws.
After a time when the program has reached some critical limits, it is easier to
program all the non-OOP’s one separately.

f. Better productivity:-
With the above-mentioned facts of using the application definitely enhances
its users overall productivity. This leads to more work done, finish a better
program, having more inbuilt features and easier to read, write and maintain.
An OOP programmer cans stitch new software objects to make completely
new programs. A good number of libraries with useful functions in
abundance make it possible.

g. Easy troubleshooting :-
lets witness some common issues or problems any developers face in their
work.

• Is this the problem in the widget file?


• Is the problem is in the Whale Flumper ?
• Will I have to trudge through that ‘sewage.c’ file?
• Commenting on all these issues related to code.

So, many a time it happens that something has gone wrong which later
becomes so brainstorming for the developers to look where the error is. Relax!
Working with OOP language you will know where to look for. This is the
advantage of using encapsulation in OOP; all the objects are self-
constrained. With this modality behavior, the IT teams get a lot of work benefits
as they are now capable to work on multiple projects simultaneously with an
advantage that there is no possibility of code duplicity.

13
APPLICATION OF OOP’S ARE :
a. Client-Server Systems

Object-oriented Client-Server Systems provide the IT infrastructure, creating


object-oriented Client-Server Internet (OCSI) applications. Here, infras-
tructure refers to operating systems, networks, and hardware. OSCI consist of
three major technologies:

 The Client Server


 Object-Oriented Programming
 The Internet

b. Object-Oriented Databases

They are also called Object Database Management Systems (ODBMS). These
databases store objects instead of data, such as real numbers and integers.
Objects consist of the following:

Attributes: Attributes are data that defines the traits of an object. This data
can be as simple as integers and real numbers. It can also be a reference to a
complex object.

Methods: They define the behavior and are also called functions or
procedures.

c. Object Oriented Databases

These databases try to maintain a direct correspondence between the real-


world and database objects in order to let the object retain their identity and
integrity. They can then be identified and operated upon.

14
d. Real-Time System Design

Real time systems inherit complexities that makes difficult to build them.
Object-oriented techniques make it easier to handle those complexities. These
techniques present ways of dealing with these complexities by providing an
integrated framework which includes schedulability analysis and behavioral
specifications.

e. Simulation And Modelling System

It’s difficult to model complex systems due to the varying specification of


variables. These are prevalent in medicine and in other areas of natural
science, such as ecology, zoology, and agronomic systems. Simulating
complex systems requires modelling and understanding interactions explicitly.
Object-oriented Programming provides an alternative approach for simplifying
these complex modelling systems.

f. Hypertext and Hypermedia

OOP also helps in laying out a framework for Hypertext. Basically, hypertext is
similar to regular text as it can be stored, searched, and edited easily. The only
difference is that hypertext is text with pointers to other text as well.

Hypermedia, on the other hand, is a superset of hypertext. Documents having


hypermedia, not only contain links to other pieces of text and information, but
also to numerous other forms of media, ranging from images to sound.

g. Neural Networking And Parallel Programming

It addresses the problem of prediction and approximation of complex time-


varying systems. Firstly, the entire time-varying process is split into several
time intervals or slots. Then, neural networks are developed in a particular time
interval to disperse the load of various networks. OOP simplifies the entire
process by simplifying the approximation and prediction ability of networks.

15
h. Office Automation Systems

These include formal as well as informal electronic systems primarily


concerned with information sharing and communication to and from people
inside as well as outside the organization. Some examples are:

i. Email
j. Word processing
k. Web calendars
l. Desktop publishing

m. CIM/CAD/CAM Systems

OOP can also be used in manufacturing and design applications as it allows


people to reduce the effort involved. For instance, it can be used while
designing blueprints, flowcharts, etc. OOP makes it possible for the designers
and engineers to produce these flowcharts and blueprints accurately.

n. AI Expert Systems

These are computer applications which are developed to solve complex


problems pertaining to a specific domain, which is at a level far beyond the
reach of a human brain.

 It has the following characteristics:


 Reliable
 Highly responsive
 Understandable
 High-performance

16
DIFFRENCE BETWEEN CLASS AND OBJECT :

17
UNIT- 2

18
1. BASIC DATA TYPES (C++) :-

Data types in C++ are mainly divided into three types:-


 Primitive Data Types: - These data types are built-in or predefined
data types and can be used directly by the user to declare variables.
Example: int , char, float, bool .etc. Primitive data types available in C++
are :-
• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character

19
 Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
 Character: Character data type is used for storing characters. Keyword
used for character data type is char. Characters typically requires 1 byte
of memory space and ranges from -128 to 127 or 0 to 255.
 Boolean: Boolean data type is used for storing boolean or logical
values. A Boolean variable can store either true or false. Keyword used
for Boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single
precision floating point values or decimal values. Keyword used for
floating point data type is float. Float variables typically requires 4 byte of
memory space.
 Double Floating Point: Double Floating Point data type is used for
storing double precision floating point values or decimal values. Keyword
used for double floating point data type is double. A double variable
typically requires 8 byte of memory space.
 void: Void means without any value. void data type represents a
valueless entity. Void data type is used for those functions which do not
return a value.
 Wide Character: Wide character data type is also a character data
type but this data type has size greater than the normal 8-bit data type.
Represented by wchar_t. It is generally 2 or 4 bytes long.
 Derived Data Types: The data-types that are derived from the
primitive or built-in data types are referred to as Derived Data Types.
These can be of four types namely:-
• Function
• Array
• Pointer
• Reference
 Function: A function is a block of code or program-segment that is
defined to perform a specific well-defined task. A function is generally
defined to save the user from writing the same lines of code again and
again for the same input. All the lines of code are put together inside a
single function and this can be called anywhere required. main() is a
default function that is defined in every program of C++.
20
Syntax:-
FunctionType FunctionName(parameters)
Example:-
Output: // C++ program to demonstrate
// Function Derived Type
#include <iostream>
using namespace std;
// max here is a function derived type
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// main is the default function derived type
int main()
{
m = max(a, b);
int a = 10, b = 20;
// Calling above function to
// find max of 'a' and 'b'
int cout << "m is " << m;
return 0;
}

Output:-
m is 20

 Array: An array is a collection of items stored at continuous memory
locations. The idea of array is to represent many instances in one
variable.
21
Syntax:-
DataType ArrayName[size_of_array];

Example:-
// C++ program to demonstrate
// Array Derived Type
#include <iostream>
using namespace std;
int main()
{
// Array Derived Type
int arr[5];
arr[0] = 5;
arr[2] = -10;
// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];
cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];
return 0;
}
Output:-
5 2 -10 5

22
 Pointers: Pointers are symbolic representation of addresses. They
enable programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures. It’s general declaration in C/C++ has
the format :
Syntax:
datatype *var_name ;

Example:-
// C++ program to illustrate
// Pointers Derived Type
#include <bits/stdc++.h>
using namespace std;
void geeks()
{
int var = 20;
// Pointers Derived Type
// declare pointer variable
int* ptr;
// note that data type of ptr
// and var must be same
ptr = &var;
// assign the address of a variable
// to a pointer
cout << "Value at ptr = "
<< ptr << "\n";
cout << "Value at var = "
<< var << "\n";
cout << "Value at *ptr = "

23
<< *ptr << "\n";
}
// Driver program
int main()
{
geeks();
}

Output:-
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20

• Reference: When a variable is declared as reference, it becomes an


alternative name for an existing variable. A variable can be declared as
reference by putting ‘&’ in the declaration.

Example:-
// C++ program to illustrate
// Reference Derived Type
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// Reference Derived Type
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
24
ref = 20;
cout << "x = " << x << endl;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl;
return 0;
}
Output:

x = 20
ref = 30

 User-Defined Data Types : The data types that are defined by the
user are called the derived data type or user-defined derived data type.

These types include:


• Class
• Structure
• Union
• Enumeration
• Typedef defined Data Type

 Class: The building block of C++ that leads to Object-Oriented


programming is a Class. It is a user-defined data type, which holds its
own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for an
object.

25
Syntax:-

Example:-
// C++ program to demonstrate
// Class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main()

26
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "GeeksForGeeks";
// accessing member function
obj1.printname();
return 0;
}
Output:-
Geekname is: GeeksForGeeks

 Structure: A structure is a user defined data type in C/C++. A structure


creates a data type that can be used to group items of possibly different
types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Example:-
// C++ program to demonstrate
// Structures in C++
#include <iostream>
using namespace std;
struct Point {
27
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
cout << arr[0].x << ", " << arr[0].y;
return 0;
}
Output:-

10, 20

 Union:- Like Structures , union is a user defined data type. In union, all
members share the same memory location. For example in the following
C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
Example:-
#include <iostream>
using namespace std;
// Declaration of union is same as the structures
union test {
int x, y;
};
int main()
{
// A union variable t

28
union test t;
// t.y also gets value 2
t.x = 2;
cout << "After making x = 2:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
// t.x is also updated to 10
t.y = 10;
cout << "After making Y = 10:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
return 0;
}

Output:-
After making x = 2:
x = 2, y = 2
After making Y = 10:
x = 10, y = 10

 Enumeration: Enumeration (or enum) is a user defined data type in C. It


is mainly used to assign names to integral constants, the names make a
program easy to read and maintain.

Syntax:-
enum State {Working = 1, Failed = 0};
29
Example:-
// Program to demonstrate working
// of enum in C++
#include <iostream>
using namespace std;
enum week { Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
{
enum week day;
day = Wed;
cout << day;
return 0;
}
Output:-
2

 Typedef :- C++ allows you to define explicitly new data type names by
using the keyword typedef. Using typedef does not actually create a new
data class, rather it defines a name for an existing type. This can increase
the portability (the ability of a program to be used across different types of
machines; i.e., mini, mainframe, micro, etc; without much changes into
the code)of a program as only the typedef statements would have to be
changed. Using typedef one can also aid in self-documenting code by
allowing descriptive names for the standard data types.

30
Syntax:-

typedef type name;

Where type is any C++ data type and name is the new name for this data
type.
This defines another name for the standard type of C++.

Example:-
// C++ program to demonstrate typedef
#include <iostream>
using namespace std;
// After this line BYTE can be used
// in place of unsigned char
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Output:-
C

 Data modifiers: - data type modifiers are used with the built-in data
types to modify the length of data that a particular data type can hold.

31
SIZE (IN
DATA TYPE BYTES) RANGE

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

Int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

Float 4

Double 8

long double 12

wchar_t 2 or 4 1 wide character

32
2. TYPE COMPATIBILITY (C++) :-
C++ is very strict with regard to type compatibility as compared to C. Type
compatibility is very close to automatic or implicit type conversion. The type
compatibility is being able to use two types together without modification and
being able to substitute one for the other without modification.
The type compatibility is categorized into following three types by the
compiler:-

 Assignment compatibility:- In assignment compatibility, if the type


of variable assigned to another variable is different it results into loss of
value of assigned variable if the size of assigned variable is large than the
size of variable to which it is assigned.
For example:-

float n1=12.5;
int n2=n1;

This assigning of float value to int type will result in loss of decimal value of
n1. However, this type compatibility will not show any error but it might give a
warning “possible loss of data”.
 Expression compatibility:-

Consider following example:-


int n=3/2;
cout<<n;

Here the result will be 1. The actual result of 3/2 is 1.5 but because of
incompatibility there will be loss of decimal value.

 Parameter compatibility:- Due to incompatibility in type of actual


parameter and formal parameters loss of data occurs.

33
For example:-

void show(int n)
{
cout<<”n=”<<n;}
void main()
{
show(8.2);
}

Here output will be n=8 due to incompatibility in actual and formal parameter
type.

3. OPERATORS IN C++
What is an operator?
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators –

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

34
 Arithmetic Operators :-
Assume variable A holds 10 and variable B holds 20, then :-

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from A - B will give -10


the first

* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator

% Modulus Operator and B % A will give 0


remainder of after an integer
division

++ Increment operator, increases A++ will give 11


integer value by one

-- Decrement operator, decreases A-- will give 9


integer value by one

 Relational Operators:-

Assume variable A holds 10 and variable B holds 20, then :-

Operator Description Example

== Checks if the values of two (A == B) is not true.


operands are equal or not, if yes
then condition becomes true.

!= Checks if the values of two (A != B) is true.


operands are equal or not, if
values are not equal then
condition becomes true.
35
> Checks if the value of left operand (A > B) is not true.
is greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand (A < B) is true.


is less than the value of right
operand, if yes then condition
becomes true.

>= Checks if the value of left operand (A >= B) is not true.


is greater than or equal to the
value of right operand, if yes then
condition becomes true.

<= Checks if the value of left operand (A <= B) is true.


is less than or equal to the value
of right operand, if yes then
condition becomes true.

 Logical Operators:-
Assume variable A holds 1 and variable B holds 0, then :-

Operator Description Example

&& Called Logical AND operator. If (A && B) is false.


both the operands are non-zero,
then condition becomes true.

|| Called Logical OR Operator. If any (A || B) is true.


of the two operands is non-zero,
then condition becomes true.

! Called Logical NOT Operator. Use !(A && B) is true.


to reverses the logical state of its
operand. If a condition is true, then
Logical NOT operator will make
false.

36
 Bitwise Operators:-
Bitwise operator works on bits and performs 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

Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

37
Assume variable A holds 60 and variable B holds 13, then :-

Operator Description Example

& Binary AND Operator copies a


(A & B) will give 12 which is
bit to the result if it exists in both
0000 1100
operands.

| Binary OR Operator copies a bit (A | B) will give 61 which is 0011


if it exists in either operand. 1101

^ Binary XOR Operator copies the


(A ^ B) will give 49 which is 0011
bit if it is set in one operand but
0001
not both.

~ Binary Ones Complement (~A ) will give -61 which is 1100


Operator is unary and has the 0011 in 2's complement form
effect of 'flipping' bits. due to a signed binary number.

<< Binary Left Shift Operator. The


left operands value is moved left A << 2 will give 240 which is
by the number of bits specified 1111 0000
by the right operand.

>> Binary Right Shift Operator. The


left operands value is moved A >> 2 will give 15 which is 0000
right by the number of bits 1111
specified by the right operand.

38
 Assignment Operators :-
Operator Description Example

= Simple assignment operator, Assigns


values from right side operands to C = A + B will assign value of A
left side operand. + B into C

+= Add AND assignment operator, It


adds right operand to the left C += A is equivalent to C = C +
operand and assign the result to left A
operand.

-= Subtract AND assignment operator,


It subtracts right operand from the
C -= A is equivalent to C = C - A
left operand and assign the result to
left operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left C *= A is equivalent to C = C *
operand and assign the result to left A
operand.

/= Divide AND assignment operator, It


divides left operand with the right
C /= A is equivalent to C = C / A
operand and assign the result to left
operand.

%= Modulus AND assignment operator,


C %= A is equivalent to C = C
It takes modulus using two operands
%A
and assign the result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and


C ^= 2 is same as C = C ^ 2
assignment operator.

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

39
 Misc Operators:-
Sr.No Operator & Description

1 size of
size of operator returns the size of a variable. For example,
sizeof(a), where ‘a’ is integer, and will return 4.

2 Condition? X : Y
Conditional operator (?). If Condition is true then it returns value of
X otherwise returns value of Y.

3 ,
Comma operator causes a sequence of operations to be performed.
The value of the entire comma expression is the value of the last
expression of the comma-separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of
classes, structures, and unions.

5 Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.

6 &
Pointer operator & returns the address of a variable. For example
&a; will give actual address of the variable.

7 *
Pointer operator * is pointer to a variable. For example *var; will
pointer to a variable var.

 Conditional Operator:- This operator evaluates a condition and


acts based on the outcome of the evaluation.

Syntax:-
Condition ? Expression2 : Expression3;

40
 Operators Precedence in C++ :-

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

41
4. SCOPE RESOLUTION OPERATOR (C++) :-

C++, scope resolution operator is (::.) It is used for following purposes:-


• To access a global variable when there is a local variable with same
name :-
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}

Output:-

Value of global x is 0
Value of local x is 10

• To define a function outside a class:-


// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include<iostream>
using namespace std;
class A

42
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
Output:-
fun() called

• To access a class’s static variables :-


// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include<iostream>
using namespace std;
class Test
{
static int x;
public:
static int y;
// Local parameter 'a' hides class member
43
// 'a', but we can access it using ::
void func(int x)
{
// We can access class's static variable
// even if there is a local variable
cout << "Value of static x is " << Test::x;
cout << "\nValue of local x is " << x;
}
};
// In C++, static members must be explicitly defined
// like this
int Test::x = 1;
int Test::y = 2;
int main()
{
Test obj;
int x = 3 ;
obj.func(x);
cout << "\nTest::y = " << Test::y;
return 0;
}
Output:-
Value of static x is 1
Value of local x is 3
Test::y = 2;

• In case of multiple Inheritance: - If same variable name exists in two


ancestor classes, we can use scope resolution operator to distinguish.

44
// Use of scope resolution operator in multiple inheritance.
#include<iostream>
using namespace std;
class A
{
protected:
int x;
public:
A() { x = 10; }
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};
class C: public A, public B
{
public:
void fun()
{
cout << "A's x is " << A::x;
cout << "\nB's x is " << B::x;
}
};
int main()
{
C c;
c.fun();
return 0;
}

45
Output :-
A's x is 10
B's x is 20

• For namespace: - If a class having the same name exists inside two
namespace we can use the namespace name with the scope resolution
operator to refer that class without any conflicts.
// Use of scope resolution operator for namespace.
#include<iostream>
int main(){
std::cout << "Hello" << std::endl;
}

Output :-
Here, cout and endl belong to the std
namespace.

• Refer to a class inside another class: If a class exists inside


another class we can use the nesting class to refer the nested class using
the scope resolution operator.
// Use of scope resolution class inside another class.
#include<iostream>
using namespace std;
class outside
{
public:
int x;
class inside
{
public:
int x;
46
static int y;
int foo();
};
};
int outside::inside::y = 5;
int main(){
outside A;
outside::inside B;
}

5. CONTROL STRUCTURE (C++) :-

What is control structure?


The Control structure is a statement used to control the flow of execution in
a program. These control structures are very helpful in implementing the
program logic.

47
There are 4 types of control structures are as follows:-
• Sequence structure
• Selection structure
• Repetition structure
• Functional call structure

 Sequence structure: - In sequential structure, the statements are


executed in the same order in which they are specified in the program.
The control flows from one statement to another in a logical sequence.
We can write as many statements as we want but all statements are
executed exactly once. It means that no statement is skipped and no
statement is repeated.
For example, we want to write a program to add two numbers. The set of
statements will be:
1. Get 1st number from user.
2. Get 2nd number from user.
3. Sum both numbers using addition (+) operator.
4. Print the sum on screen.
All these statements are written and executed only once. And the program
executes them sequentially to find sum.

 Selection structure: - A selection structure selects a statement or set


of statements to execute on the basis of a condition. In this structure,
statement or set of statements is executed when a particular condition
is true and ignored when the condition is false. There are different types
of selection structures in C++ like:

 IF Statement
 IF...ELSE Statement
 SWITCH Statement

 IF statement: - When you use the “if “statement, you check a condition.
If the condition is met (true), a piece of code is executed. However if the
condition is false, the piece of code in the loop body is skipped.

48
Syntax:-

if (condition)
;
{
Statement 1;
}
Statement 2;
Statement 3;

Example:-
int main()
{
int age;
age = 70;
if (age>60)
{
cout<<”Incorrect age”<<endl;
}
return 0;
}
Output:-
Incorrect age

 IF … ELSE statement:- The “if…else” structure tells the compiler what to


do when a condition is met (true) and when the condition is not met
(false). Whereas, the “if” structure only specifies what the compiler must
do when the condition is met (true).

49
Syntax:-

if (condition)
{
Statement 1;
}
else
{
Statement 2;
}
Statement 3;

Example:-
Let’s enhance the example of the “if” statement. Now, when the condition
(age< 60) is true we display the message “correct age”, and when the
condition is false we display the message “incorrect age”:
int main()
{
int age;
age = 70;
if (age<=60)
{
cout<<”Correct age”<<endl;
}else
{
cout<<”Incorrect age”<<endl;
}
return 0;
}

50
Output:-

Incorrect age

 SWITCH statement: - The “switch…case” statement tests the value of an


expression against a list of conditions. When a match is found, the
statements associated with that condition are executed. In the case of a
“switch…case” statement, the conditions are constants. Each constant is
a “case” (in the body of the “switch….case” statement).
Syntax:-
switch(expression)
{
case1;
Block-of Statements1;
case2:
Block-of Statements2;
case3:
Block-of Statements3;
default:
Block-of Statements4;
}
Statement5;

 Repetition structure: - A repetition structure executes a statement


or set of statements repeatedly. It is also known as iteration
structure or loop.
This structure is also based on conditions. Statements are repeated as long
as a condition remains true.
There are 3 different types of repetition structures in C++ like:
 WHILE Loop
 DO...WHILE Loop
 FOR Loop
51
 WHILE Loop: - For as long as the loop condition is true, the “while”
loop continues to execute. When the condition becomes false it stops
looping, and the compiler transfers the control to the statement
immediately following the loop. In the “while”, the loop condition is
checked before the first iteration of the loop.
Syntax:-

while (condition is true)


{
Statement1;
}
Statement 2;

Example:-
int main()
{
int x=0;
while(x<=5)
{
cout<<x<<endl;;
x=x+1;
}
return 0;
}
Output:-

0
1
2
3
4
5

52
Understanding the statements of the above program:33339999999

• The variable x is initialized to zero


• Next, the loop condition requires to repeat the loop till the value of x=5
• Each time the loop executes, the cout statement prints the value of x on
screen. In addition, the statement x=x+1, increments the value of x by 1.
This statement is required so that the value x becomes greater than 5 and
the loop condition becomes false.

 DO…WHILE Loop:- The “do… while” loop construct is similar to the


“while” loop. The only difference between the two is that the “do…while”
loop executes the loop once and then evaluates the loop condition,
whereas the “while” loop evaluates the loop condition first. Therefore,
even when the loop condition is false, the “do… while” loop will execute at
least once but the while loop will not.

Syntax:-

int main()
{
int x=0;
while(x<=5)
{
cout<<x<<endl;;
x=x+1;
}
return 0;
}

53
Output:-
0
1
2
3
4
5

Understanding the statements of the above program:


• The variable x is initialized to zero
• The loop executes, and the cout statement prints the value of x on
screen. In addition, the statement x=x+1, increments the value of x by 1.
• After the first execution, the loop condition is evaluated. Now, the value of
the variable x is 1. So the condition x<=5 is true and the loop continues to
execute till the value of x becomes 6.
• When the value of the variable x is 6 the loop condition is not met, and the
control is transferred to the “return 0” statement.

 FOR Loop:- A “for” loop, like other loop structures, executes a piece of
code as many times as you want. You use a “for” loop when you know the
number of times you want to execute a piece of code.
Syntax:-
for(initial value; condition; increment)
{
Statement1;
}
Statement 2;

 Functional Call structure: - Function call is a type of statement that


moves the control to another block of code. The control returns back after
executing all statements in the block. The remaining statements are
executed immediately after the function call when the control is returned.

54
UNIT - 3

55
FUNCTION C++

POP (Procedural Oriented Programming) language like C, programs are


divided into different functions but in OOP (Object Oriented Programming)
approach program is divided into objects where functions are the
components of the object.

C++ functions definition:-

Function definition is a part where we define the operation of a function. It


consists of the declarator followed by the function body.

Syntax

return_type function_name( parameter_list )


{
function body;
}

Defining a function is a way of specifying how the operation is to be done


when the function is called.

56
Illustration of function call

Whenever we declare a function a part of the memory is reserved for that


function and when we define the function is stored in that memory block.

Let’s suppose the function is stored at the address 0x111. When we call the
function in the main program compiler goes to that memory location 0x111
where the code is executed as defined.

After the execution, the compiler returns the result to the program without
concerning any details how the result was obtained.

Though it takes time for execution, it becomes handy when dealing with
huge programs.

57
General structure of a function in C++ program

//Structure of C++ program

#include <iostream> using

namespace std;

return_type function_name(parameter_list); //function prototype void

main()

........

function_name(); //function call

........

return_type function_name(parameter_list) //function defintion

........

function definition

........

58
FUNCTION PROTOTYPING:-

While writing a program, we can’t use a function without specifying its type
or without telling the compiler about it.

So before calling a function, we must either declare or define a function.

Thus, declaring a function before calling a function is called function


declaration or prototype which tells the compiler that at some point of the
program we will use the function of the name specified in the prototype.

Syntax

return_type function_name(parameter_list);

Note: function prototype must end with a semicolon.

Here, return_type is the type of value that the function will return. It can be
int, float or any user-defined data type.

function_name means any name that we give to the function. However, it


must not resemble any standard keyword of C++.

Finally, parameter_list contains a total number of arguments that need to


be passed to the function.

59
CALL BY REFERENCE:-

The call by reference method of passing arguments to a function copies the


reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This
means that changes made to the parameter affect the passed argument.

To pass the value by reference, argument reference is passed to the


functions just like any other value. So accordingly you need to declare the
function parameters as reference types as in the following function swap(),
which exchanges the values of the two integer variables pointed to by its
arguments.
// function definition to swap the values.

void swap(int &x, int &y) {s

int temp;

temp = x; /* save the value at address x */

x = y; /* put y into x */

y = temp; /* put x into y */


return;
}

60
For now, let us call the function swap() by passing values by reference as
in the following example −
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}

When the above code is put together in a file, compiled and executed, it
produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

61
INLINE FUNCTION:-
C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
Following is an example, which makes use of inline function to return max
of two numbers −
#include <iostream> using
namespace std; inline int
Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

62
FUNCTION OVERLOADING:-
When we have multiple functions with the same name but different
parameters, then they are said to be overloaded. This technique is used to
enhance the readability of the program.
There are two ways to overload a function, i.e. −

● Having different number of arguments


● Having different argument types

Function overloading is normally done when we have to perform one single


operation with different number or types of arguments.

Function Overloading in C++

The following example shows how function overloading is done in C++,


which is an object oriented programming language −
#include <iostream>
using namespace std;
void addnum(int,int);
void addnum(int,int,int);
int main() {
addnum (5,5);
addnum (5,2,8);
return 0;
}
void addnum (int x, int y) { cout<<"Integer
number: "<<x+y<<endl;
}
void addnum (int x, int y, int z) {
cout<<"Float number: "<<x+y+z<<endl;
}
It will produce the following output −
Integer number: 10
Float number: 15
63
LIBRARY FUNCTION:-
The C++ Standard Library can be categorized into two parts −
• The Standard Function Library − This library consists of general- purpose,
stand-alone functions that are not part of any class. The function library is
inherited from C.
• The Object Oriented Class Library − This is a collection of classes and
associated functions.

Standard C++ Library incorporates all the Standard C libraries also, with
small additions and changes to support type safety.

The Standard Function Library


The standard function library is divided into the following categories −
● I/O,
● String and character handling,
● Mathematical,
● Time, date, and localization,
● Dynamic allocation,
● Miscellaneous,
● Wide-character functions,
The Object Oriented Class Library
Standard C++ Object Oriented Library defines an extensive set of classes
that provide support for a number of common activities, including I/O,
strings, and numeric processing. This library includes the following −
● The Standard C++ I/O Classes
● The String Class
● The Numeric Classes
● The STL Container Classes
● The STL Algorithms
● The STL Function Objects
● The STL Iterators
● The STL Allocators
● The Localization library
● Exception Handling Classes
● Miscellaneous Support Library

64
UNIT – 4

65
COMPARISON OF CLASS AND C- STRUCTURE :-

Comparison Chart:-

BASIS FOR
STRUCTURE CLASS
COMPARISON

Basic If access specifier is not If access specifier is not


declared, by default all declared, by default all
member are 'public'. members are 'private'.

Declaration struct structure_name{ class class_name{


type struct_element 1; data member;
type struct_element 2; member function;
type struct_element 3; };
.
};

Instance Instance of 'structure' is Instance of a 'class' is


called 'structure variable'. called 'object'.

Polymorphism Not supported Supports polymorphism


and inheritance and a class can also be
inherited.

Nature Value type Reference type

Memory is Stack Heap


allocated on

Null values Not possible Can have null values

Requires No Yes
constructor and
destructor

66
 Structure: - A structure is a collection of variables of dissimilar data
types, all referenced by one name. A structure declaration forms a template
that is used to create an instance of the structure.

Syntax:-

struct sname
{
type struct_element1;
type struct_element2;
type struct_element3;
.
}
variable1, variable2, . .
;

The keyword ‘struct’ defines to the compiler that a structure is being declared.
The ‘sname’ represents the name given to the structure. The structure
declaration is always terminated by a semicolon, as it is considered as a
statement.

You can declare the instances of the structure before its termination as done
in above code (variable1, variable2) or you can declare the instance of
structure in main( ), by writing the instance name preceded with the name of
the structure.

67
Example:-
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;
/*Assigning the values of each struct member here*/
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
/* Displaying the values of struct members */
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:-

Student Name is: Steve


Student Id is: 1234
Student Age is: 30

68
 Class: - Class in OOP defines a new type which contains data members
and member function, that are used to access the data members of the class.
The instances of classes are called “objects” each of which has the same
organization as a class. The class is a logical abstraction, whereas an object
has a physical existence.

Syntax:-
class Class_Name
{
Private:
Data-Type Variable_Name;
Function declaration or Function
Definition;
Public:
Data-Type Variable_Name;
Function declaration or Function
Definition;
};

Here, the class is a keyword which declares to the compiler that a class has
been declared. The main feature of OOP is data hiding which is
accomplished by providing three access specifiers that are “public”, “private”,
“protected”. If you do not specify any access specifier in the class while
declaring data members or member functions, by default all are considered
private.

The public access specifier allows, functions or data to be accessed by other


parts of your program. The private members of the class can only be
accessed by a member of that class only. The protected access specifier is
applied during inheritance. Once you declare the access specifier, it can not
be changed throughout the program.

69
Example:-

class test
{
int a, b;
public:
void input ();
{
cout<<"Enter Value of a and b";
cin>>a>>b;
}
void output ()
{
cout<<"A="<<a<<endl<<"B="<<b;
}
};
Key Differences between Structure and Class:-
1. The main difference between structures and classes is that by default,
all member of the structure are public. In contrast, by default, all the
members of the class are private.
2. A structure is considered as the value type whereas; a class is a
reference type.
3. At the time of instantiating a structure, the memory is allocated on a
stack. As against, in class, the memory is allotted on the heap.
4. No structure member can have a null value. Conversely, the variables
of a class can have null values.
5. In order to initialize the member of a class, the constructors and
destructors are used. On the contrary, the structure can initialize its
members automatically.
6. In variables in the structure can not be initialized during the declaration
while in case of class, this can be done.

Similarities:-
• In C++, both the structure and class are syntactically equivalent.
• Both structure and class can declare some of their members private.
• The name of a structure or class can be used as a stand-alone type.
• Both structure and class support the mechanism of inheritance.
70
CREATING OBJECTS:-
There are two different methods for creating objects of the class:-

(1) We can create object at the time of specifying a class after the
closing curly bracket.

Example:-
Class test
{
int a,b;
public:
void input ();
void ouput ();
}t1,t2,t3;
Here, t1, t2 and t3 are the objects of class test.

(2) We can create object inside the main function using name of the
class.
The general syntax for creating object inside main function is as below:

Class_Name Object_Name;
Example:-
Test t1, t2, t3;
Here, t1, t2 and t3 are the objects of class test.

71
How to Access Class Members?
The data member and member function declared as a public can be accessed
directly using the object of the class. But the data member and member
function declared as private cannot be accessed directly using the object of
the class.

We can access private member of the class using public member of the
class.
The general syntax for accessing public member using object is given below:-

Object_Name. Data_Member = value;


Object_Name. Member_Function (Argument_List);
Example:
T1. input ();
T1. output ();
Example:-
class Test
{
int b;
Public:
int a;
void inputb()
{
b=20;
}
};
int main()
{
Test t1;
T1.a=10; //works because a is public
T1.b=20; //error because b is private
T1.inputb (); //works because inputb () is public
return 0;
}

72
ARRAYS WITHIN CLASS :-
• Arrays can be declared as the members of a class.
• The arrays can be declared as private, public or protected members of the
class.
• To understand the concept of arrays as members of a class, consider this
example.
Example -1:-
#include<iostream>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

73
Output:-
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
Example-2:-
#include<iostream.h>
class arraydemo
{
int a[6];
public:
void getelts()
{
cout<<”Enter 6 numbers in the array:”<<endl;
for(int i=0;i<6;i++)
{
cin>>a[i];
}
}
void show()
{
cout<<”\nArray elements are”<<endl;
for(int i=0;i<6;i++)
{
cout<<a[i]<<endl;
}
}
};
void main()
{
arraydemo obj;
obj.getelts();
obj.show();
}

74
Output:-
Enter 6 numbers in the array:
5
6
2
1
7
4
9
Array elements are
5
6
2
1
7
4
9

ARRAYS OF OBJECT:-
Like data member of the class we can also create an array of objects.
Array of object is useful when we want to create large number of objects of the
same class.
• Like array of other user-defined data types, an array of type class can also
be created.
• The array of type class contains the objects of the class as its individual
elements.
• Thus, an array of a class type is also known as an array of objects.
• An array of objects is declared in the same way as an array of any built-in
data type.

75
Syntax (array of object) :-
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;
method1();
method2();
----------
methodN();
};
class-name obj[ size ];

Example -1:-

#include<iostream.h>
class Student
{
int rollno;
char name[20];
public:
void Input();
void Output();
};
void Student::Input()
{
cout<<"Enter Roll Number:";
cin>>rollno;
cout<<"Enter Name:";
cin>>name;
}
void Student::Output()
{
cout<<"Roll Number:"<<rollno<<endl;
cout<<"Name:"<<name<<endl;
}
int main()
{
Student S[3];
76
int i;
for(i=0;i<3;i++)
S[i].Input();
for(i=0;i<3;i++)
S[i].Output();
return 0;
}

Output:-
In above example we create an array of object using following statement:
Student S [3]; Here, we create 3 objects. First object refer to S [0], second
object refer to S[1] and third object refer to S[2].
Thus in array of object an object can be identified using the name of the array
and index.

Enter Roll Number: 1


Enter Name: Mukesh
Enter Roll Number: 2
Enter Name: Ruchin
Enter Roll Number: 3
Enter Name: Mehul
RollNumber:1
Name: Mukesh
RollNumber:2
Name: Ruchin
RollNumber:3
Name: Mehul

77
Example -2:-

#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
for(i=0; i < 4; i++)
obs[i].setX(i);
for(i=0; i < 4; i++)
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";
getch();
}

Output:-
obs[0].getX(): 0

obs[1].getX(): 1

obs[2].getX(): 2

obs[3].getX(): 3

78
Example-3:-
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;
cout<<"\n\tEnter Employee Name : ";
cin>>Name;
cout<<"\n\tEnter Employee Age : ";
cin>>Age;
cout<<"\n\tEnter Employee Salary : ";
cin>>Salary;
}
void PutData() //Statement 2 : Defining PutData()
{
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;
}
};
void main()
{
int i;
Employee E[3]; //Statement 3 : Creating Array of 3 Employees
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
}
79
Output:-
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000

In the above example, we are getting and displaying the data of 3 employee
using array of object. Statement 1 is creating an array of Employee Emp to
store the records of 3 employees.

80
OBJECTS AS FUNCTION ARGUMENT:-
In C++ we can pass object as a function argument and also return an object
from the function.

An object can be passed to the function using two methods:


 Call By value: In which copy of the object is passed to the function.

 Call By reference: In which an address of the object is passed to the


function.

Example -1:-

#include<iostream.h>
class Demo
{
int a,b;
public:
Demo()
{
a=0;
b=0;
}
Demo(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"A="<<a<<endl<<"B="<<b<<endl;
}
Demo sum(Demo D2);
};
Demo Demo::sum(Demo D2)
{
81
Demo D3;
D3.a = a + D2.a;
D3.b = b + D2.b;
return D3;
}
int main()
{
Demo B1(1,2);
Demo B2(3,4);
Demo B3;
B3 =B1.sum(B2);
B3.display();
return 0;
}

Output:-

A=4
B=6

Above program performs the addition of data member of two objects and store
it in the third object.
Consider the function defined inside class:

Demo sum(Demo D2);


It accepts one object of the class Demo as an argument and returns an object
to the calling function.
When we call the function using following statement:
B3 =B1.sum(B2);
Data member of object B1 is passed to the function implicitly while data
member of object B2 is passed to the function explicitly. After performing
addition of data member of two objects B1 and B2 it will store it in the data
member of third object and return that object.
82
Example-2 :-

#include<iostream.h>
class time
{
int hr,min;
public:
void gettime(int h,int m)
{
hr=h;
min=m;

}
void puttime(void)
{
cout<<hr<< “ hrs and “;
cout<<min<<” mins “<<endl;

}
void sum(time, time); //declaration of function with object as
argument
};
void time :: sum(time t1, time t2)
{
min=t1.min+t2.min;
hr=min/60;
min=min%60;

hr=hr+t1.hr+t2.hr;
}
83
int main()
{
time obj1,obj2, obje3;
obj1.gettime(2, 45);
obj2.gettime(3, 30);
obj3.sum(obj1,obj2); //obj3=obj1+obj2;
cout<<” obj1= “;
obj1.puttime();
cout<<”obj2= “;
obj2.puttime();
cout<<”obj3= “;
obj3.puttime();
return 0;
}

Output:-

Obj1= 2 hrs and 45 mins


Obj2= 3 hrs and 30 mins
Obj3= 6 hrs and 15 mins

An object can also be passed to the non member functions, however this non
member function cannot access the private data members of the class and
can access only public member functions through the object passed as
argument.

84
UNIT – 5

85
Constructor and Destructor

INTRODUCTION

In the previous unit, we have discussed concept of Objects and Class


and their use in object oriented programming . In this unit we shall
discuss about constructors and destructors and their use in memory
management for C++ programming.

C++ allows different categories of data types, that is, built-in data types
(e.g., int, float, etc.) and user defined data types (e.g., class). We can
initialize and destroy the variable of user defined data type (class), by
using constructor and destructor in object oriented programming .
Constructor is used to create the object in object oriented programming
language while destructor is used to destroy the object. The constructor
is a function whose name is same as the object with no return type. The
name of the destructor is the name of the class preceded by tilde (~).

First we will discuss briefly about constructor and destructor and then
move on to the types of constructor and memory management.
Whenever an object is created, the special member function , that is,
constructor will be executed automatically . Constructors are used to
allocate the memory for the newly created object and they can be
overloaded so that different form of initialization can be accommodated.
If a class has constructor , each object of that class will be initialized . It is
called constructor because it constructs the value of data members of
the class.

Let us take an example to illustrate the syntax and declaration of


constructor and destructor, inside a class in object oriented
programming.

86
Example: A constructor is declared and defined as follows:

// class with constructor


class integer
{
int m, n;
public:
integer (void); // constructor declared
…………
…………
};
integer :: integer (void) // constructor defined
{
m = 0, n = 0;
}

Characteristics of Constructors:-
A constructor for a class is needed so that the compiler automatically
initializes an object as soon as it is created . A class constructor if defined
is called whenever a program creates an object of that class The
constructor functions have some special characteristics which are as
follows:
• They should be declared in the public section.
• They are invoked directly when an object is created.
• They don’t have return type, not even void and hence can’t return
any values.
• They can’t be inherited; through a derived class, can call the base
class constructor.
• Like other C++ functions, they can have default arguments.
• Constructors can’t be virtual.
• Constructor can be inside the class definition or outside the class
definition.
• Constructor can’t be friend function.
• They can’t be used in union.
• They make implicit calls to the operators new and delete when
memory allocation is required.

When a constructor is declared for a class, initialization of the class objects


becomes necessary after declaring the constructor.

87
Limitations of Constructor

C++ constructors have the following limitations:

• No return type A constructor cannot return a result, which means that


we cannot signal an error, during the object initialization. The only way
of doing it is to throw an exception from a constructor.
• Naming A constructor should have the same name as the class, which
means we cannot have two constructors that both take a single
argument.
• Compile time bound At the time when we create an object, we must
specify the name of a concrete class which is known at compile time.
There is no way of dynamic binding constructors at run time.
• There is no virtual constructor We cannot declare a virtual
constructor. We should specify the exact type of the object at compile
time, so that the compiler can allocate memory for that specific type. If
we are constructing derived object, the compiler calls the base class
constructor first and the derived class hasn't been initialized yet. This is
the reason why we cannot call virtual methods from the constructor.

Parameterized Constructor:-

We can write a constructor in C++ which can accept parameters for its
invocation. Such constructor that can take the arguments are called
parameterized constructor. In other words; “Declaring a constructor with
arguments hides the default constructor”. This means that we can
always specify the arguments whenever we declare an instance of the
class.

To illustrate parameterized constructor well, let us write the syntax and take
one example:

class <cname>
{
//data
public: cname(arguments); // parameterized constructor
.........
.........
};
Examples:
class student
{
char name[20]; int rno;
public: student(char,int); //parameterized constructor
};
student :: student(char n,int r)
{
name=n; rno=r;
}

88
Multiple constructor in a class:-

A class can have multiple constructors that assign the fields in different
ways . Sometimes it's beneficial to specify every aspect of an object 's data
by assigning parameters to the fields, but other times it might be
appropriate to define only one or a few.

Example of multiple constructor in a class has been shown above:

Copy Constructor:-
Sometimes it is required to copy the value of data member of one object
into another object while creating it. This can be accomplished using the
concept of copy constructor.
The constructor that accepts reference to the object as an argument is
known as copy constructor.
A copy constructor is used to declare and initialize an object from another
object. For example, the statement integer 12(11);
would define the object 12 and at the same time initialize it to the value of
11. Another form of this statement is integer 12 = 11;
Thus the process of initializing through a copy constructor is known as copy
initialization.
A copy constructor is always used when the compiler has to create a
temporary object of a class object. The copy constructors are used in the
following situations
• The initialization of an object by another object of the same class.
• Return of objects as a function value.
• Stating the object as by value parameters of a function.

89
The syntax of copy constructor is: class_name :: class_name(class_name
&ptr)

Class Rectangle
Height, Width;
Rectangle (Rectangle &r)
int Height
Width = r.Width;
}
}
class <cname>
{
//data
public: cname(arguments); // parameterized constructor
};

Examples:
class student
{
char name[20];
int rno;
public: student(char,int); //parameterized constructor
};
student :: student(char n,int r)
{
name=n;
rno=r;
}

90
Program has been given below:

#include<iostream>
#include<conio.h>
using namespace
std; class student
{
int roll;
char
name[30];
public:
student() // default constructor
{
roll =10;
strcpy(name,"x"
);
}
student( student &O) // copy constrcutor
{
roll =O.roll;
strcpy(name,
O.name);
}
void input_data()
{
cout<<"\n Enter roll no :"; cin>>roll;
cout<<"\n Enter name :";
cin>>name;
}
void show_data()
{
cout<<"\n Roll no :"<<roll;
cout<<"\n Name
:"<<name;
}
};
int main()
{
student s; // default construtor
s.show_data();
student A(s); // copy constructor
A.show_data(
); getch();
return 0;
}

91
Constructor Overloading:-
When more than one constructor function is defined in a class, then it is
called constructor overloading or use of multiple constructor in a class. It is
used to increase the flexibility of a class by having more number of
constructors for a single class.
Overloading constructors in C++ programming gives us more than one way
to initialize objects in a class.
To illustrate the constructor overloading, let us take following examples:

92
DESTRUCTORS

Destructors are functions that are complimentary to constructors. A


destructor, as the name implies, is used to destroy the objects that have
been created by using constructor. They de-initialize objects when they are
destroyed. A destructor is invoked when an object of the class goes out of
scope, or when the memory occupied by it is de allocated using the delete
operator. A destructor is a function that has the same name as that of the
class but is prefixed with a ~ (tilde). For example the destructor for the
class students will bear the name ~student(). Destructor takes no
arguments or specifies a return value, or explicitly returns a value not even
void. It is called automatically by the compiler when an object is destroyed.
A destructor cleans up the memory that is no longer required or accessible.
To understand the syntax of destructor let us take following example.

#include<iostream.h>

#include<conio.h>

class student // student is a class

{ public : ~student() // destructor declaration

{ cout <<"Thanx for using this program" <<endl;

} };

main()

{ clrscr(); student s1;

// s1 is an object

getch();

93
Program:

#include<iostream>
#include<conio.h>
using namespace std;
class xyz
{
public:
xyz()
{
cout<<"\n Constructor ";
}
~xyz() // use of destructor with -- tilde
{
cout<<"\n Destructor ";
}
};
int main()
{
{
xyz B;
}
getch();
return 0;
}

(Example has been given above)

94
PROGRAMS ON CONSTRUCTOR & DESTRUCTOR

#include<iostream.h>
#include<conio.h> class stu
{
private: char name[20],add[20]; int roll,zip;
public: stu ( );//Constructor
~stu( );//Destructor void read( );
void disp( );
};
stu :: stu( )
{
cout<<”This is Student Details”<<endl;
}
void stu :: read( )
{
cout<<”Enter the student Name”; cin>>name;
cout<<”Enter the student roll no “; cin>>roll;
cout<<”Enter the student address”; cin>>add;
cout<<”Enter the Zipcode”; cin>>zip;
}
void stu :: disp( )
{ cout<<”Student Name :”<<name<<endl; cout<<”Roll no is :”<<roll<<endl;
cout<<”Address is :”<<add<<endl; cout<<”Zipcode is :”<<zip;
}
stu : : ~stu( )
{
cout<<”Student Detail is Closed”;
}
void main( )
{
stu s; clrscr( );
s.read ( );
s.disp ( );
getch( );
}

95
Output:

Enter the student Name

Sushil

Enter the student roll no

01

Enter the student address

Delhi

Enter the Zipcode

110092

Student Name : Sushil

Roll no is : 01

Address is : Delhi

Zipcode is :110092

96
UNIT – 6

97
Operator Overloading in C++:-
The process of giving special meaning to the existing c++ operator is known
as "Operator Overloading".
Using the concept of operator overloading we can use operators with object of
the class.
For example: We can use + to perform addition of two integer or floating point
numbers. In the same way we can overload + operator so that we can perform
addition of two objects of the class.
When you overload the existing operator the basic syntax rules of the operator
is not changed. It remains as it is.
In order to overload particular operator you need to use special function
known as operator function.

How to define Operator Function


The general syntax for defining operator overloading is given below:
Return-type operator op (Argument List)
{
}
Here,
Return-type indicates the type of the value that is return by the function.
Operator is the name of the operator function.
Op is the operator to which you want to overload
Argument List indicates number of arguments need to be passed. The
operator function can be either member function or friend function.

98
Unary Operator Overloading:-
Unary operator having one operand so generally we need to pass one
argument to the operator function.
If you define operator function as a member function then it will accept no
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function.
If you define operator function as a friend function then it will accept one
argument. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass object as an
argument explicitly.
Once the operator function is defined you can invoke operator function in
following different ways:
op ObjectName;
or
// For Member Function
ObjectName.operator ();
// For Friend Function
Operator op (ObjectName)

Binary Operator Overloading:-


Binary operator having two operands so generally we need to pass two
arguments to the operator function.
If you define operator function as a member function then it will accept one
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function and other object is passed explicitly
to the function.
If you define operator function as a friend function then it will accept two
arguments. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass two objects as an
argument explicitly.

99
Once the operator function is defined you can invoke operator function in
following different ways:
ObjectName1 op ObjectName2;
Or
// For Member Function ObjectName1.operator (ObjectName2);
// For Friend Function
Operator op (ObjectName1, ObjectName2);

Operator Overloading
There are some rules or restrictions for overloading operators. These rules are
as given below:
1. You can overload only existing operator. New operator can not be created.
2. you can not overload following operators:

Size of operator Conditional operator (? :)

Scope resolution operator (::)


Class member access operator (., .*)
3. By overloading operator you can not change the syntax rules of operator.
4. You cannot use friend function to overload following operators:
= Assignment operator.
() Function call operator.
{} Subscripting operator.
-> Class member access operator.
5. When you overload unary operator using member function it will take no
explicit argument. But if you overload unary operator using friend function
then it will take one explicit argument.
6. When you overload binary operator using member function it will take one
explicit argument. But if you overload binary operator using friend function
then it will take two explicit arguments.
7. when you overloaded operators cannot have default arguments.

100
Overload Unary Operator using Member Function
Unary operator having one operand so generally we need to pass one
argument to the operator function.
If you define operator function as a member function then it will accept no
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function.
Consider following example to overload unary operator ++ using member
function
#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
void operator ++()
{
count++;
}
void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1;
++d1;
d1.display();
++d1;
d1.display();
return 0;
}
Output:
Count = 1
Count = 2

101
Overload Unary Operator using Friend Function

If you define operator function as a friend function then it will accept one
argument. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass object as an
argument explicitly.
Consider following example to overload unary operator ++ using friend
function.

#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
friend void operator ++(demo &d)
{
d.count++;
}
void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1; operator
++(d1); d1.display();
operator ++(d1);
d1.display(); return 0;
}
Output:
Count = 1
Count = 2

102
Overload Binary Operator using Member Function
Binary operator having two operands so generally we need to pass two
arguments to the operator function.
If you define operator function as a member function then it will accept one
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function and other object is passed explicitly
to the function.
Consider following example to overload binary operator + using member
function.
#include <iostream.h> class demo
{
int x,y; public:
demo()
{ x=0;
y=0;
}
demo(int a, int b)
{
x=a; y=b;
}
demo operator +(demo &d)
{
demo d3;
d3.x = x + d.x;
d3.y = y + d.y;
return d3;
}
void display()
{
cout<<"X="<<x<<endl; cout<<"Y="<<y<<endl;
}
};
int main()
{
demo d1(2,3);

103
demo d2(4,5);
demo d
d3 = d1 + d2;
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8

104
Overload Binary Operator using Friend Function
If you define operator function as a friend function then it will accept two
arguments. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass two objects as an
argument explicitly.
Consider following example to overload binary operator + using friend
function.

d3 = operator + (d1,d2);
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8

String Manipulation using Operator Overloading:-


C++ allows us the facility of manipulate strings using the concept of operator
overloading.
For example we can overload + operator to concate two strings. We can
overload == operator to compare two strings.
Consider Following Example in which we overload + operator to concate two
strings.

105
Type Conversion in C++:-
In a mixed expression constants and variables are of different data types . The
assignment operations causes automatic type conversions between the
operands as per the rules. The type of data to the right of an assignment
operator is automatically converted to the data type of variable on the left
which is called as the Type Conversion. Example :- int x; float y = 20.123; x =
y;

Type Conversion: Basic type to class


• The conversion from basic type to the class type can be performed
by two ways:

1. Using constructor
2. Using Operator Overloading

Using Constructor:-
• We can use constructor to perform type conversion during the object
creation.
• Consider the following example with class ‘Time’ in which we want to
assign total time in minutes by integer variable ‘duration’.
• To achieve that we have implemented one constructor function which
accepts one argument of type integer as follow:

Here, we have created an object “t1” of class “Time” and during the creation
we have assigned integer variable “duration”. It will pass time duration to the
constructor function and assign to the “hrs” and “min” members of the class
“Time”.

We have to note that during type conversion using the constructor we can
pass only one argument and we can do type conversion at the type of
initialization only.

106
Using Operator Overloading:-
• We can also achieve type conversion by operator overloading.
• We can overload assignment operator for this purpose.
• Above example of Time class can be rewritten for type conversion using
operator overloading concept to overload the assignment operator (=) as
follow:
/* Program to convert from basic type to class type using operator overloading*/

#include
"iostream.h"
#include "conio.h"
class Time
{
int hrs,min; public:
void display();
void operator=(int); // overloading function
};
void Time::display()
{
cout<<hrs<< ": Hour(s) "<<endl ;
cout<<min<<": Minutes"<<endl ;
}
void Time::operator=(int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl; hrs=t/60;
min=t%60;
}
void main()
\
{
clrscr(); Time t1;
int duration;
cout<<"Enter time duration in minutes"; cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl; t1=duration;
t1.display();
cout<<"object t1 assignment operator 2nd method..."<<endl;
t1.operator=(duration);
t1.display();
getch();
}
107
Conversion from class type to basic type:-
The constructor functions do not support conversion from a class to basic
type. C++ allows us to define a overload casting operator that convert a class
type data to basic type.
The general syntax of an overloaded casting operator function, also referred
to as a conversion function, is :
In the below example, operator double () converts a class object to type
double.
operator typename()
{
// Program statement
}
Example :

vector :: operator double ()


{
double sum = 0 ;
for ( int i = 0 ; i < size ; i++ )
sum = sum + v[i] * v[i] ;
return sqrt ( sum ) ;

The casting operator should satisfy the following conditions :-


1. It must be a class member.
2. It must not specify a return type.
3. It must not have any arguments. The values inside the function used for
conversion belongs to the object that invoked the function. So, function does
not need an argument.

2) Conversion from one class to another class type :


We have just seen data conversion techniques from a basic to class type and
a class to basic type. But sometimes we would like to convert one class data
type to another class type.

108
Example :

obj1 = obj2 ; // obj1 and obj2 are objects of different classes

Explanation :-
obj1 is an object of class one and obj2 is an object of class two. The class two
type data is converted value is assigned to the obj1. Since the conversion
takes place from class two to class one, two is known as the source and one
is known as the destination class.

Such conversion between objects of different classes can be carried out by


either a constructor or a conversion function. Which form to use, depends
upon where we want the type-conversion function to be located, whether in
the source class or in the destination class.

Casting operator function - Operator typename () -:

This function converts the class object of which it is a member to typename.


The typename may be a built-in type or a user defined one( another class type
). In the case of conversions between objects, typename refers to the
destination class. Therefore, when a class needs to be converted, a casting
operator function can be used. The conversion takes place in the source and
the result is given to the destination class.

109
The following program uses classes and shows how to convert data of
one type to another

#include <iostream>
using namespace std;
class stock2 ;
class stock1
{
int code , item ;
float price ; public :
stock1 ( int a , int b , int c )
{
code = a ; item
= b ; price = c ;
};
void disp ()
{
cout << " code " << code << " \n " ; cout
<< " items " << item << " \n " ;
cout << " price per item Rs. " << price << " \n " ;
};
int getcode ()
{ return code; }; int
getitem ()
{ return item ; }; int
getprice ()
{ return price ; };
operator float ()
{
return ( item*price ) ;
};
};
class stock2
{
int code ;
float val ;

110
public : stock2 ()
{
code = 0; val = 0 ;
};
stock2( int x , float y )
{
code = x ; val = y ;
};
void disp ()
{
cout << " code " << code << " \n " ;
cout << " total value Rs. " << val << " \n " ;
};
stock2( stock1 p )
{
code = p.getcode() ;
val = p.getitem() * p.getprice() ;
};
};
int main()
{
stock1 i1 ( 101 , 10 ,125.0 ) ;
stock2 i2 ;
float tot_val = i1; i2 = i1 ;
cout << " Stock Details : Stock 1 type " << " \n " ; i1.disp ();

cout << " Stock Value " << " - " ; cout << tot_val << " \n " ;
cout << " Stock Details : Stock 2 type " << " \n " ; i2.disp () ;
return 0 ;
}

111
UNIT - 7

112
INHERITANCE
In object-oriented programming , inheritance is the mechanism of basing
an object or class upon another object (prototype based inheritance) or class
(class-based inheritance), retaining similar implementation.

Also defined as deriving new classes (sub classes) from existing ones such
as super class or base class and then forming them into a hierarchy of
classes.

In most class-based object-oriented languages, an object created through


inheritance, a "child object", acquires all the properties and behaviors of the
"parent object" , with the exception of: constructors, destructor, overloaded
operators and friend functions of the base class.

Inheritance allows programmers to create classes that are built upon existing
classes, to specify a new implementation while maintaining the same
behaviors (realizing an interface), to reuse code and to independently
extend original software via public classes and interfaces.

The relationships of objects or classes through inheritance give rise to


a directed graph.

Inheritance was invented in 1969 for Simula and is now used throughout
many object-oriented programming languages such as Java, C++ or
Python.

An inherited class is called a subclass of its parent class or super class.

The term "inheritance" is loosely used for both class-based and prototype-
based programming, but in narrow use the term is reserved for class-based
programming (one class inherits from another), with the corresponding
technique in prototype-based programming being instead called delegation
(one object delegates to another).

Inheritance should not be confused with subtyping. In some languages


inheritance and subtyping agree. whereas in others they differ; in general,
subtyping establishes an relationship, whereas inheritance only reuses
implementation and establishes a syntactic relationship, not necessarily a
semantic relationship (inheritance does not ensure behavioral subtyping).

113
To distinguish these concepts, subtyping is also known as interface
inheritance, whereas inheritance as defined here is known asimplementation
inheritance or code inheritance.

Still, inheritance is a commonly used mechanism for establishing subtype


relationships.

Inheritance is contrasted with object composition, where one object contains


another object (or objects of one class contain objects of another class);
see composition over inheritance.

Composition implements a has-a relationship, in contrast to the is-a


relationship of subtyping.

TYPES OF INHERITANCE:-
There are various types of inheritance, based on paradigm and specific
language.

SINGLE INHERITANCE
In single inheritance, a class is allowed to inherit from only one class. i.e.
one sub class is inherited by one base class only

114
MULTIPLE INHERITANCE
where one class can have more than one superclass and inherit features
from all parent classes.

MULTILEVEL INHERITANCE
where a subclass is inherited from another subclass. It is not uncommon that
a class is derived from another derived class as shown in the figure ".
The class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.

The class B is known as intermediate base class because it provides a link


for the inheritance between A and C. The chain ABC is known as inheritance
path.

A derived class with multilevel inheritance is declared as follows:

ClassA(...);// Base class


ClassB:publicA(...);// B derived from A
ClassC:publicB(...);// C derived from B
This process can be extended to any number of levels.

115
HIERARCHICAL INHERITANCE
This is where one class serves as a superclass (base class) for more than
one sub class. For example, a parent class, A, can have two subclasses B
and C. Both B and C's parent class is A, but B and C are two separate
subclasses.

HYBRID INHERITANCE
Hybrid inheritance is when a mix of two or more of the above types of
inheritance occurs. An example of this is when class A has a subclass B
which has two subclasses, C and D. This is a mixture of both multilevel
inheritance and hierarchal inheritance.

116
NEED OF PROTECTED MEMBERS:-
The private members of a class cannot be directly accessed outside the
class. Only methods of that class can access the private members directly.

As discussed previously, however, sometimes it may be necessary for a


subclass to access a private member of a superclass. If you make a private
member public, then anyone can access that member.

So, if a member of a superclass needs to be (directly) accessed in a


subclass and yet still prevent its direct access outside the class, you must
declare that member protected.

Following table describes the difference


Modifier Class Subclass World
public Y Y Y
protected Y Y N
private Y N N

Following program illustrates how the methods of a subclass can directly


access a protected member of the superclass.

117
For example, let's imagine a series of classes to describe two kinds of
shapes: rectangles and triangles.

These two shapes have certain common properties height and a width (or
base).
This could be represented in the world of classes with a class Shapes from
which we would derive the two other ones :

Rectangle and Triangle

/**
* A class Shape that holds width and height
* of any shape
*/
publicclassShape
{
protecteddouble height; // To hold height.
protecteddouble width; //To hold width or base
/**
* The setValue method sets the data
* in the height and width field.
*/
publicvoidsetValues(double height, double width)
{
this.height = height;
this.width = width;
}
}

118
Program : (Rectangle )

/**
* This class Rectangle calculates
* the area of rectangle
*/
publicclassRectangleextendsShape
{
/**

* The method returns the area


* of rectangle.
*/
publicdoublegetArea()
{
return height * width; //accessing protected members
}
}

Program : (Triangle)

/**
* This class Triangle calculates
* the area of triangle
*/
publicclassTriangleextendsShape
{
/**
* The method returns the area
* of triangle.
*/
publicdoublegetArea()
{
return height * width / 2; //accessing protected members
}

119
Program : (TestProgram)

/**
* This program demonstrates the Rectangle and
* Triangle class, which inherits from the Shape class.
*/
publicclassTestProgram
{
publicstaticvoidmain(String[] args)
{
//Create object of Rectangle.
Rectangle rectangle = new Rectangle();

//Create object of Triangle.


Triangle triangle = new Triangle();

//Set values in rectangle object


rectangle.setValues(5,4);

//Set values in trianlge object


triangle.setValues(5,10);

// Display the area of rectangle.


System.out.println("Area of rectangle : " +
rectangle.getArea());

// Display the area of triangle.


System.out.println("Area of triangle : " +
triangle.getArea());
}
}

Output :

120
Area of rectangle : 20.0

Area of triangle : 25.0

APPLICATION OF INHERITANCE:-

Inheritance is used to co-relate two or more classes to each other.

OVERRIDING

Illustration of method overriding


Many object-oriented programming languages permit a class or object to
replace the implementation of an aspect—typically a behavior—that it has
inherited. This process is called overriding.

Overriding introduces a complication: which version of the behavior does an


instance of the inherited class use—the one that is part of its own class, or
the one from the parent (base) class?

121
The answer varies between programming languages, and some languages
provide the ability to indicate that a particular behavior is not to be
overridden and should behave as defined by the base class.

For instance, in C#, the base method or property can only be overridden in a
subclass if it is marked with the virtual, abstract, or override modifier, while in
programming languages such as Java, different methods can be called to
override other methods

An alternative to overriding is hiding the inherited code.

CODE REUSE

Implementation inheritance is the mechanism whereby a subclass re-


uses code in a base class.

By default the subclass retains all of the operations of the base class, but
the subclass may override some or all operations, replacing the base-class
implementation with its own.

In the following Python example,

subclasses SquareSumComputer and CubeSumComputer override the


transform() method of the base class SumComputer.

The base class comprises operations to compute the sum of the squares
between two integers.

The subclass re-uses all of the functionality of the base class with the
exception of the operation that transforms a number into its square,
replacing it with an operation that transforms a number into its square and
cube respectively.

The subclasses therefore compute the sum of the squares/cubes between


two integers.

122
In most quarters, class inheritance for the sole purpose of code reuse has
fallen out of favor.

The primary concern is that implementation inheritance does not provide


any assurance of polymorphic substitutability—an instance of the reusing
class cannot necessarily be substituted for an instance of the inherited class.

An alternative technique, explicit delegation, requires more programming


effort, but avoids the substitutability issue.

In C++ private inheritance can be used as a form of implementation


inheritance without substitutability.

Whereas public inheritance represents an "is-a" relationship and delegation


represents a "has-a" relationship, private (and protected) inheritance can be
thought of as an "is implemented in terms of" relationship.

Another frequent use of inheritance is to guarantee that classes maintain a


certain common interface;

that is, they implement the same methods. The parent class can be a
combination of implemented operations and operations that are to be
implemented in the child classes.

Often, there is no interface change between the supertype and subtype- the
child implements the behavior described instead of its parent class.

123
UNIT- 8

124
MANAGING CONSOLE I\O OPERATIONS

The standard C++ library is iostream and standard input / output functions in
C++ are:

1. cin
2. cout

There are mainly two types of console I/O operations form:

1. Unformatted console input output


2. Formatted console input output

Formatted console input output operations:-


In formatted console input output operations we uses following functions to
make output in perfect alignment.

In industrial programming all the output should be perfectly formatted due to


this reason C++ provides many function to convert any file into perfect
aligned format.

These functions are available in header file <iomanip>. iomanip refers input
output manipulations.

A) width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n )

125
Example:

#include<iostream>

#include<iomanip>

Using namespace std;


int main()

int x=10;
cout<<setw(20)<<variable;

return 0;

Output

10

B) fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;

126
Example:

#include<iostream>
#include<iomanip>
using namespace std;
int main()

int x=10; cout<<setw(20);


cout<<setfill('#')<<x;
return 0;

Output

##################10

D) Precision (n)

This method is used for setting floating point of the output.

Syntax:

cout<<setprecision('int n')<<variable;

127
Example:

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}

Output:-

10.123

E) setflag(arg 1, arg,2)
This function is used for setting format flags for output.
Syntax:
setiosflags(argument 1, argument 2);
F) unsetflag(arg 2)
This function is used to reset set flags for output.
Syntax:
resetiosflags(argument 2);
G) setbase(arg)
This function is used to set basefield of the flag.
Syntax:
setbase(argument);

128
Unformatted console input output operations:-

These input / output operations are in unformatted mode. The following are
operations of unformatted console input / output operations:

A) void get()

It is a method of cin object used to input a single character from keyboard. But
its main property is that it allows wide spaces and newline character.
Syntax:
char c=cin.get();

Example:
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}

Output

129
B) void put()

It is a method of cout object and it is used to print the specified character on


the screen or monitor.

Syntax:

cout.put(variable / character);

Example:

#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}

Output

130
C) getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with multiple
spaces.
Syntax:

char x[30];

cin.getline(x,30);

Example:

include<iostream>

using namespace std;

int main()

cout<<"Enter name:";

char c[10];

cin.getline(c,10); //It takes 10 charcters as input;

cout<<c<<endl;

return 0;

Output
Enter name :Divyanshu

Divyanshu

131
Input / output streams:-

In the Java API, an object from which we can read a sequence of bytes is
called an input stream. An object to which we can write a sequence of bytes
is called an output stream.

These sources and destinations of byte sequences can be—and often are—
files, but they can also be network connections and even blocks of memory.
The abstract classes InputStream and OutputStream are the basis for a
hierarchy of input/output (I/O) classes.

NOTE :

These input/output streams are unrelated to the streams that you saw in the
preceding chapter. For clarity, we will use the terms input stream,
output stream, or input/output stream whenever we discuss streams that
are used for input and output.

Byte-oriented input/output streams are inconvenient for processing


information stored in Unicode (recall that Unicode uses multiple bytes per
character). Therefore, a separate hierarchy provides classes, inheriting from
the abstract Reader and Writer classes, for processing Unicode characters.
These classes have read and write operations that are based on two-byte
char values (that is, UTF-16 code units) rather than byte values.

In Java, streams are the sequence of data that are read from the source
and written to the destination.

An input stream is used to read data from the source. And, an output
stream is used to write data to the destination.
132
class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

For example, in our first Hello World example, we have used System.out to
print a string. Here, the System.out is a type of output stream.
Similarly, there are input streams to take input.

133
Types of Streams

Depending upon the data a stream holds, it can be classified into:

● Byte Stream
● Character Stream

Byte Stream

Byte stream is used to read and write a single byte (8 bits) of data.

All byte stream classes are derived from base abstract classes called
InputStream and OutputStream.

Character Stream

Character stream is used to read and write a single character of data.

All the character stream classes are derived from base abstract classes
Reader and Writer.

134
UNIT-9

135
Files operation

I. Opening & closing a files


II. Programming with a files
File Handling In C++
Files are used to store data in a storage device permanently. File handling
provides a mechanism to store the output of a program in a file and to
perform various operations on it.

A stream is an abstraction that represents a device on which operations of


input and output are performed. A stream can be represented as a source or
destination of characters of indefinite length depending on its usage

In C++ we have a set of file handling methods. These include ifstream,


ofstream, and fstream. These classes are derived from fstrembase and from
the corresponding iostream class. These classes, designed to manage the
disk files, are declared in fstream and therefore we must include fstream
and therefore we must include this file in any program that uses files.

In C++, files are mainly dealt by using three classes fstream, ifstream,
ofstream available in fstream headerfile.

ofstream: Stream class to write on files

ifstream: Stream class to read from files

fstream: Stream class to both read and write from/to files.

136
In C++, you open a file, you must first obtain a stream. There
are the following three types of streams:
 input
 output
 input/output

Create an Input Stream

To create an input stream, you must declare the stream to be of


class ifstream. Here is the syntax:

ifstream fin;

Create an Output Stream

To create an output stream, you must declare it as class ofstream.


Here is an example:

ofstream fout

Create both Input/Output Streams

Streams that will be performing both input and output operations


must be declared as class fstream. Here is an example:

fstream fio;

137
Opening a File in C++:-
Once a stream has been created, next step is to associate a file with it. And
thereafter the file is available (opened) for processing.

Opening of files can be achieved in the following two ways :

1. Using the constructor function of the stream class.


2. Using the function open().

The first method is preferred when a single file is used with a stream.
However, for managing multiple files with the same stream, the second
method is preferred. Let's discuss each of these methods one by one.

Opening File Using Constructors

We know that a constructor of class initializes an object of its class when it


(the object) is being created. Same way, the constructors of stream classes
(ifstream, ofstream, or fstream) are used to initialize file stream objects with
the filenames passed to them. This is carried out as explained here:

To open a file named myfile as an input file (i.e., data will be need from it
and no other operation like writing or modifying would take place on the file),
we shall create a file stream object of input type i.e., ifstream type. Here is
an example:

ifstream fin("myfile", ios::in) ;

The above given statement creates an object, fin, of input file stream. The
object name is a user-defined name (i.e., any valid identifier name can be
given). After creating the ifstream object fin, the file myfile is opened and
attached to the input stream, fin. Now, both the data being read from myfile
has been channelised through the input stream object.

138
Now to read from this file, this stream object will be used using the getfrom
operator (">>"). Here is an example:

char ch;
fin >> ch ; // read a character from the
file >> amt ; // a floating-point number form the file

Similarly, when you want a program to write a file i.e., to open an output file
(on which no operation can take place except writing only). This will be
accomplish by

1. creating ofstream object to manage the output stream


2. associating that object with a particular file Here is an example,

ofstream fout("secret" ios::out) ; // create


ofstream object named as fout

This would create an output stream, object named as fout and


attach the file secret with it.

Now, to write something to it, you can use << (put to operator) in
familiar way. Here is an example,

int code = 2193 ;


fout<<code<<"xyz" /* will write value of code
and "xyz" to fout’s associated file
namely "secret" here. */

The connections with a file are closed automatically when the input and the
output stream objects expires i.e., when they go out of scope.

(For example, a global object expires when the program terminates). Also,
you can close a connection with a file explicitly by using the close() method :

fin.close() ; // close input connection to file fout.close() ;


// close output connection to file
Closing such a connection does not eliminate the stream; it just
disconnects it from the file. The stream still remains there. For example,
139
after the above statements, the streams fin and fout still exist along with the
buffers they manage.

You can reconnect the stream to the same file or to another file, if required.
Closing a file flushes the buffer which means the data remaining in the
buffer (input or output stream) is moved out of it in the direction it is ought to
be.
For example, when an input file's connection is closed, the data is moved
from the input buffer to the program and when an output file's connection is
closed, the data is moved from the output buffer to the disk file.

Opening Files Using Open() Function


There may be situations requiring a program to open more than one file.
The strategy for opening multiple files depends upon how they will be used.

If the situation requires simultaneous processing of two files, then you need
to create a separate stream for each file.

However, if the situation demands sequential processing of files (i.e.,


processing them one by one), then you can open a single stream and
associate it with each file in turn.

To use this approach, declare a stream object without initializing it, then use
a second statement to associate the stream with a file. For example,

140
ifstream fin; // create an
input stream
fin.open("Master.dat", ios::in); // associate fin
stream with file Master.dat
: // process
Master.dat
fin.close();
// terminate association
with Master.dat
fin.open("Tran.dat", ios::in); // associate fin
stream with file Tran.dat
:
// process
Tran.dat
fin.close(); // terminate
association

The above code lets you handle reading two files in succession. Note that
the first file is closed before opening the second one.

This is necessary because a stream can be connected to only one file at a


time.

The Concept of File Modes

The filemode describes how a file is to be used : to read from it, to write to it,
to append it, and so on.

When you associate a stream with a file, either by initializing a file stream
object with a file name or by using the open() method, you can provide a
second argument specifying the file mode, as mentioned below :

stream_object.open("filename", (filemode) ) ;

The second method argument of open(), the filemode, is of type int, and you
can choose one from several constants defined in the ios class.

141
List of File Modes in C++

Following table lists the filemodes available in C++ with their meaning:-

Constant Meaning Stream Type

ios :: in It opens file for reading, i.e., in input mode. ifstream


ios :: out It opens file for writing, i.e., in output mode. ofstream
This also opens the file in ios :: trunc
mode, by default. This means an existing
file is truncated when opened, i.e., its
previous contents are discarded.
ios :: ate This seeks to end-of-file upon opening of the ofstream
file. ifstream
I/O operations can still occur anywhere
within the file.
ios :: app This causes all output to that file to ofstream
be appended to the end. This value
can be used only with files capable of
output.
ios :: trunc This value causes the contents of a pre- ofstream
existing file by the same name to be
destroyed and truncates the file to zero
length.
ios :: This cause the open() function to fail if the ofstream
nocreate file does not already exist. It will not create
a new file with that name.
ios :: This causes the open() function to fail if the ofstream
noreplac file already exists.
e This is used when you want to create a new
file and at the same time.
ios :: binary This causes a file to be ofstream
opened in binary mode. ifstream
By default, files are
opened in text mode.
When a file is opened in text mode,
various character translations may take
place, such as the conversion of carriage-
return into newlines.
However, no such character translations
occur in file opened in binary mode.

142
If the ifstream and ofstream constructors and the open() methods take two
arguments each, how have we got by using just one in the previous
examples ? As you probably have guessed, the prototypes for these class
member functions provide default values for the second argument (the
filemode argument). For example, the ifstream open() method and
constructor use ios :: in (open for reading) as the default value for the mode
argument, while the ofstream open() method and constructor use ios :: out
(open for writing) as the default.

The fstream class does not provide a mode by default and, therefore, one
must specify the mode explicitly when using an object of fstream class.

Both ios::ate and ios::app place you at the end of the file just opened. The
difference between the two is that the ios::app mode allows you to add data
to the end of the file only, when the ios::ate mode lets you write data
anywhere in the file, even over old data.

You can combine two or more filemode constants using the C++ bitwise OR
operator (symbol |). For example, the following statement :

ofstream fout;
fout.open("Master", ios :: app | ios :: nocreate);

will open a file in the append mode if the file exists and will abandon the file
opening operation if the file does not exist.

To open a binary file, you need to specify ios :: binary along with the file
mode, e.g.,
fout.open("Master", ios :: app | ios :: binary);

or,
fout.open("Main", ios :: out | ios :: nocreate | ios
:: binary);

143
Closing a File in C++:-
As already mentioned, a file is closed by disconnecting it with the
stream it is associated with. The close() function accomplishes this
task and it takes the following general form :

stream_object.close();

For example, if a file Master is connected with an ofstream object fout, its
connections with the stream fout can be terminated by the following
statement :

fout.close() ;

C++ Opening and Closing a File Example

Here is an example given, for the complete understanding on:

• how to open a file in C++ ?


• how to close a file in C++ ?

Let's look at this program.

/* C++ Opening and Closing a File


* This program demonstrates, how
* to open a file to store or retrieve
* information to/from it. And then how
* to close that file after storing
* or retrieving the information to/from it. */

144
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ofstream fout;
ifstream fin;
char fname[20];
char rec[80],
ch;
clrscr();cout<<"Enter file name: ";
cin.get(fname, 20); fout.open(fname, ios::out);
if(!fout)
{
cout<<"Error in opening the file "<<fname; getch();
exit(1);
}
cin.get(ch);
cout<<"\nEnter a line to store in the file:\n"; cin.get(rec, 80);
fout<<rec<<"\n";
cout<<"\nThe entered line stored in the filesuccessfully..!!";
cout<<"\nPress any key to see...\n"; getch();
fout.close();
fin.open(fname, ios::in); if(!fin)
{
cout<<"Error in opening the file "<<fname; cout<<"\nPress
any key to exit..."; getch();
exit(2);
}
cin.get(ch);
fin.get(rec, 80);
cout<<"\nThe file contains:\n";
cout<<rec;
cout<<"\n\nPress any key to exit...\n"; fin.close();
getch();
}

145
Programming with a files:-
Below is the implementation by using ifstream &
ofstream classes.
Ifstream:- The ifstream is a file stream class used for file
handling. To use ifstream header file fstream is used. It is used
for reading input from the file. In order to read from a file an object
of type ifstream is created.
Use as ifstream:- Reading a text file is very easy using
an ifstream (input file stream).
1. Include the necessary headers. #include <fstream> using namespace
std;
2. Declare an input file stream ( ifstream ) variable. ...
3. Open the file stream. ...
4. Check that the file was opened. ...
5. Read from the stream in the same way as cin . ...
6. Close the input stream

/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>
/* fstream header file for ifstream, ofstream, fstream classes */
#include <fstream> using
namespacestd;
// Driver Code
int main()
{
// Creation of ofstream class object ofstream fout;
string line;
// by default ios::out mode, automatically deletes
// the content of file. To append the content, open in ios:app

146
// fout.open("sample.txt", ios::app) fout.open("sample.txt");
// Execute a loop If file successfully opened while (fout) {
// Read a Line from standard input getline(cin, line);
// Press -1 to exit if (line == "-1")
break;
// Write line in file fout << line << endl;
}
// Close the File
fout.close();
// Creation of ifstream class object to read the file
ifstream fin;
// by default open mode = ios::in mode fin.open("sample.txt");
// Execute a loop until EOF (End of File) while (fin) {
// Read a Line from File
getline(fin, line); // Print line in Console cout << line << endl;
} // Close the file
fin.close();
return 0;
}

Below is the implementation by using ofstream class.


ofstream. This data type represents the output file stream and is used to
create files and to write information to files. 2. ifstream. This data type
represents the input file stream and is used to read information from files.
So far, we have been using the iostream standard library, which
provides cin and cout methods for reading from standard input
and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This
requires another standard C++ library called fstream, which
defines three new data types –
147
Sr.No Data Type & Description

1 Ofstream
This data type represents the output file stream and is used to
create files and to write information to files.
2 Ifstream
This data type represents the input file stream and is used to read
information from files.

3 Fstream
This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can
create files, write information to files, and read information from
files.

Difference between using ifstream and ofstream with cin and cout. ...
It says that ifstream is used to read data from a file, while ofstream is used
to write data.
Examples:-
fstream
/* File Handling with C++ using fstream class object*/
/* To write the Content in File */
/* Then to read the content of file*/
#include <iostream>
/* fstream header file for ifstream, ofstream,
fstreamclasses */
#include
<fstream>
using
namespace
std;
// Driver Code
int main()
{
// Creation of fstream class object fstream
fio;
string line;
// by default openmode = ios::in|ios::out mode

148
// Automatically overwrites the content of file, to
append
// the content, open in ios:app
// fio.open("sample.txt",
ios::in|ios::out|ios::app)
// ios::trunc mode delete all conetent
before open
fio.open("sample.txt", ios::trunc | ios::out |
ios::in);
// Execute a loop If file successfully Opened while (fio) {
// Read a Line from standard input getline(cin, line);
// Press -1 to exit if (line == "-1")
break;
// Write line in file fio << line << endl;
}
// Execute a loop untill EOF (End of File)
// point read pointer at beginning of file
fio.seekg(0, ios::beg); while (fio) {
// Read a Line from File
getline(fio, line);
// Print line in Console cout
<< line << endl;
}
// Close the file fio.close();
return 0;
}

149
UNIT-10

150
Virtural & friend function
 Pointers to objects
 This pointers
 Virtual function
 Pure virtual function
 Concept of late & early binding

Pointer to objects:-
A Variable That Holds an Address value is called a Pointer variable or
simply pointer. We already discussed about pointer that's point to Simple
data types likes int, char, float etc. So similar to these type of data type,
Objects can also have an address, so there is also a pointer that can
point to the address of an Object, This Pointer is Known as This Pointer.

This pointer:-

Every Object in C++ has access to its own address through an important
pointer called This Pointer. The This Pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be
used to refer to the invoking object. Whenever a member function is
called, it is automatically passed an implicit arguments that is This pointer
to the invoking object (i.e. The object on which the function is invoked).

The This pointer is passed as a hidden argument to all Nonstatic member


function calls and is available as a local variable within the body of all
Nonstatic functions. This Pointer is a constant pointer that holds the
memory address of the current object. This pointer is not available
in static member functions as static member functions can be called
without any object (with class name)

151
Let's have an simple example of This pointer.

/* This Pointer: InfoBrother */


#include<iostream>
using namespace std;
class Point
{
private:
int x;

public:
voidsetx(int a) //simple function.
{
this->x=a;
}
};

main()
{
Point obj1; //1st Object of Class Point.
Point obj2; //2nd Object of Class point.
obj1.setx(10); //function calling using 1st object.
obj2.setx(30); //function calling using 2nd object.
return 0;
}
In Above Example, there is an simple class having two objects, and a
simple function that take an integer as an parameter, and initialize it to
variable x. Now in above Example, Might be you have a Question, That

How Setx() function understand which object 'x' value to be set?

So the Answer is, When the function is called the address of the calling
object is passed implicitly. so in order to understand, consider the
following statement.
obj1.setx( 10 );
Here value 10 is passed explicitly to the function setx() but at the same
time Address of obj1 is passed implicitly to the function. " Int a" holds the
value 10, and the address of obj1 stored in a pointer named " this " pointer.

Similarly when obj2 calls the function of the class, " This " pointer holds
address of obj2 to refer obj2's data member. at shown in figure:
152
C++ DECLARATION AND USES OF OBJECT POINTERS:
Just like Other Pointers, the object pointers are declared by placing in
front of a object pointer's name. The Syntax is:

class_name*Object_pointer_name;
In above Syntax, class_Name is the name of an already defined class and
object_pointer_name is the pointer to an object of this class type. For
example: To declared an Pointer ptr an an object pointer of class Date, We
shall write:

Date *ptr;
In Above syntax, Date is already defined class. When accessing members
of a class using an object pointer, the Error Operator -> is used instead of
Dot Operator. Let's take an simple example, This Example illustrates how
to access an object given a pointer to it.

153
154
155
Virtual function:-
A Virtual Function is a function that is declared as Virtual in a base class
and redefined in one or more derived classes. Thus, each derived class
can have its own version of a Virtual Function.

If there are Member functions with same name in base class and derived
class, Virtual Functions gives Programmer Capability to call member
function of different class by a same function call depending upon different
context. This feature in C++ Programming is known as Polymorphism
which is one of the important feature of Object Oriented Programming. If a
base Class and derived Class has same function and if we write code to
access that function using pointer of base class then, The function in the
base class is executed even, if the object of derived class is referenced
with that pointer variable. This can be demonstrated by this Example:
/* Virtual Function Concept: InfoBrother:*/
#include<iostream>
using namespace std;
class Base //Base Class:
{
public:
void display() //Simple function to display some content.
{
cout<<" Base Class "<<endl;
}
};
class Derived: public Base //Derived class. Using Inheritance concept.
{
public:
void display() //redefine Same function.
{
cout<<" Derived Class "<<endl;
}
};
main()
{
Base *ptr; //pointer object of type Base.
Derived obj; //object of type Derived
ptr->display(); //function calling using Base-Class object:
ptr=&obj; //pointer point to Address of Derived Class.

156
ptr->display(); //function calling using pointer, that point to Derived
class.
return 0;
}

Check Output
In Above Example, even if the object of derived class Derived is put in
pointer to Base Class, display() of the base class is executed. so in order
to Execute the member function of Derived Class, we Need to
use Virtual Keyword in the base class along with display() Function,
which makes that function existing in appearance only but, we can't call
that function. So let's try same example using Virtual Keyword.
/* Virtual Function: InfoBrother:*/
#include<iostream>
using namespace std;
class Base //Base Class:
{
public:
virtual void display() //Virtual Function.
{
cout<<" Base Class "<<endl;
}
};
class Derived: public Base //Derived class. Using Inheritance concept.
{
public:
void display() //redefine same Function.
{
cout<<" Derived Class "<<endl;
}
};
main()
{
Base *ptr; //pointer object of type Base.
Derived obj; //object of type Derived
ptr->display(); //function calling using Base-Class object:
ptr=&obj; //pointer point to Address of Derived Class.
ptr->display(); //function calling using pointer, that point to Derived class.
return 0;
}

157
After the function of Base is made Virtual, code ptr->display() will call the
display() of the derived class depending upon the content of pointer. in this
example, display() function of two different classes are called with same
code which is one of the example of Runtime Polymorphism in C++
Programming using Virtual function.

Pure virtual function:-


In C++ Programming, sometimes inheritance is used only for the better
visualization of data and we don't need to create any object of base class.
For example: if we want to calculate area of different objects like Circle
and Square then, we can inherit these classes from a shape, because it
helps to visualize the problem but, we don't need to create any object of
Shape. in such case, we can declare Shape as abstract class if we try to
create object of a Abstract class, compiler shows error.

A pure Virtual function or abstract function in C++ is a virtual function for


which we don't have implementation, we only declare it. If Expression =0
is added to a virtual function then, that function is becomes pure Virtual
function.

Adding =0 to virtual function does not assign value, it simply indicates the
virtual function is a pure function.
/*Abstract Class. (because of Pure virtual function)*/
class Base
{
public:
void display(); //Not virtual function:
virtual void display(); //virtual function but Not Pure:
virtual void display()=0; //Pure Virtual function:
};

158
Here, Base is an Abstract class, because it has a pure Virtual function, so
no objects of class Base can be directly created. Base is explicitly mean
to be a base class. Let's have an complete example for Pure Virtual
Function.

/* Pure Virtual Function example: InfoBrother:*/

#include <iostream>
using namespace std;

class Shape /* Abstract class */


{
protected:
float l;

public:
voidget_data() /*this function is not virtual. */
{
cin>>l;
}
virtual float area() = 0; /* Pure virtual function */
};
class Square : public Shape //derived class.
{
public:
float area()
{
return l*l;
}
};
class Circle : public Shape //derived class.
{
public:
float area()
{
return 3.14*l*l;
}
};

int main()
{

159
Square squ; //object of type Square:
Circle cir; //Object of type Circle:
cout<<"Enter length to calculate area of a square: ";
squ.get_data();
cout<<"Area of square: "<<squ.area();
cout<<"\n\nEnter radius to calculate area of a circle:";
cir.get_data();
cout<<"Area of circle: "<<cir.area();
return 0;

Concept of late and early binding:-


Binding refers to the process of converting identifiers (such as variable and
performance names) into addresses. Binding is done for each variable and
functions. For functions, it means that matching the call with the right
function definition by the compiler. It takes place either at compile time or at
runtime.

Early Binding (compile-time time polymorphism) As the name


indicates, compiler (or linker) directly associate an address to the function
call. It replaces the call with a machine language instruction that tells the
mainframe to leap to the address of the function.
By default early binding happens in C++. Late binding (discussed below) is
achieved with the help of virtual keyword)

160
// CPP Program to illustrate early binding.
// Any normal function call (without virtual)
// is binded early. Here we have taken base
// and derived class example so that readers
// can easily compare and see difference in
// outputs.
#include<iostream>
usingnamespacestd;

classBase
{
public:
voidshow() { cout<<" In Base \n"; }
};

classDerived: publicBase
{
public:
voidshow() { cout<<"In Derived \n"; }
};

intmain(void)
{
Base *bp = newDerived;

// The function call decided at


// compile time (compiler sees type
// of pointer and calls base class
// function.
bp->show();
return0;
}

161
Late Binding : (Run time polymorphism) In this, the compiler adds code
that identifies the kind of object at runtime then matches the call with the
right function definition (Refer this for details). This can be achieved by
declaring a virtual function.

// CPP Program to illustrate late binding


#include<iostream>
usingnamespacestd;
classBase
{
public:
virtualvoidshow() { cout<<" In Base \n"; }
};
classDerived: publicBase
{
public:
voidshow() { cout<<"In Derived \n"; }
};
intmain(void)
{
Base *bp = newDerived;
bp->show(); // RUN-TIME POLYMORPHISM
return0;
}

162

You might also like