0% found this document useful (0 votes)
14 views

Oop Java Mu Notes

Uploaded by

Abhijit Logavi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Oop Java Mu Notes

Uploaded by

Abhijit Logavi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

UNIT – I

CHAPTER – 01

Classes and Objects


Chapter Structure :

1.0 PROGRAM AND PROGRAMMING

1.1 PROGRAMMING LANGUAGES

1.2 PROCEDURE ORIENTED PROGRAMMING

1.3 NEED OF OBJECT ORIENTED PROGRAMMING

1.4 OBJECT ORIENTED PROGRAMMING

1.5 COMPARISON OF PROCEDURAL AND OBJECT ORIENTED

APPROACH

1.6 BENEFITS OF OOP

1.7 ADVANTAGES OF OOPs

1.8 OBJECT-ORIENTED LANGUAGES

1.9 APPLICATIONS OF OOPS

1.0 PROGRAM AND PROGRAMMING


____________________________________________________________________________________________
As you might be aware, the two essential components of any computer system are hardware and
software. Both hardware and software have their own sets of functionalities which can be
interdependent or independent of each other. A computer system is designed to produce the
desired results by making the functionalities of both the hardware and the software to converge.
The hardware is what we can see, touch and feel e.g. keyboard, mouse, visual display units like
monitors, printers etc. Once it has been designed and manufactured to provide a certain set of
functionalities, it can not be modified easily. Any modification in the hardware requires lot of
effort, time and money. That is why we don’t change our hardware very frequently. If the
computers are required to carry out only a few predefined operations, these can be very easily
embedded in the design of its hardware.But this kind of a computer completely lacks flexibility.
In order to provide flexibility to perform some different operation in a computer, most of the
existing hardware requires to be replaced with a newer one; whenever a new operation is added
or older operations are to be abandoned or modified.Therefore, a computer system always
contains a minimum basic hardware which is used by the software to provide lot of flexibility of
operations. The software can be modified / replaced with lesser effort, time and money.
As such, a computer is essentially a data processing machine which requires two kinds of inputs
for its operations and these are: data and instructions. The hardware of a computer can not
produce the desired results unless it is given the requisite instructions and data by the user(s).
The data is what needs to be processed by the hardware and the instructions (from within the set
of its functionalities) tell this (minimum basic) hardware how to process that data step by step
within the realms of set of functionalities so that expected results are achieved.Do you know
what is software all about? The software deals with the instructions.The examples of software
are Microsoft Office, Microsoft Windows 7, Red Hat Linux, Railways Reservation System,
Microsoft Internet Explorer, Google Search Engine etc. A program as an independent entity or as
part of a software is intended to instruct the hardware to carry out specific task(s) to the
satisfaction of the user(s) by providing specific outcomes. So how do you define a program?
A program can be defined to be a set of instructions written in a programming language which
are given in a fixed sequence to the hardware of a specific computer and executed by its
hardware to produce predetermined and expected outcomes. The instructions in a program are
written mostly in natural languages (e.g. English, Hindi, French, German, and Chinese etc.)
following the syntax (form) and semantics (meaning) of the programming language chosen for
writing the program. There are a variety of programming languages available for writing the
programs e.g. BASIC, C, C++, Java, Prolog, Lisp, HTML, PHP etc. The sequence of instructions
is very important because if the sequence is not correct, the expected results cannot be achieved
by the program. Now, let us see what does programming mean to us? The meaning of the term
programming (or computer programming) has been changing rapidly since the idea of a first
program was envisaged. Initially the computers were used to solve the mathematical problems
with the help of calculations. Hartee in 1950 suggested that the process of preparing a calculation
for a machine can be broken down into two parts, ‘programming’ and ‘coding’. He described
programming as the process of drawing up the schedule of the sequence of individual operations
required to carry out the calculation.Before the availability of assemblers, coding was in fact, a
very tedious and time consuming task. Soon, programming became the major activity in this
process. In 1958, Booth proposed that the process of organizing a calculation can be divided into
two parts, a) the mathematical formulation, and b) the actual programming. With the passage
of time, the definition of programming has kept on evolving and at present programming is
considered to be the process of writing programs and may include activities as diverse as
designing, writing, testing, debugging and maintaining the code of a program.
In normal conversation, programming is described as the process of instructing the computer to
do something desired and useful for the user with the help of a programming language.

1.1 PROGRAMMING LANGUAGES


____________________________________________________________________________________________
You must appreciate the fact that the programming languages are created by, we, human beings.
These languages are used to communicate instructions to the machines especially computers so
that the programs can control the behaviour of the hardware of the machines to get desired
results. Basically, the hardware of the computers understands only the language of the hardware
which is called the machine language. The hardware is unable to understand and decipher any
program written in any other programming language. Moreover, every type of a CPU has its own
machine language. Therefore, in order to make the hardware of a computer understand the
instructions contained in a program written in any other programming language, a mechanism
called ‘translator’ is required. This translator converts the program written in programming
languages other than the native machine language of the CPU (hardware) into the native machine
language of a particular CPU on which this program is intended to be executed.
Every programming language must have its own translator for the programs written in it to be
executed or run on the computer hardware. Various types of translators available can be
categorized into assemblers, interpreters or compilers. The primitive or the first generation of
programming languages were called machine languages and the symbols like ‘0’ and ‘1’ were
used to write programs under this category of programming languages. The second generation of
programming languages were called the assembly languages and mainly used mnemonics to
construct a program. Both of these generations of programming languages were CPU dependent
i.e., every type of a CPU will have its own machine and assembly language. The third generation
of programming languages was called high level languages as these programming languages
were independent of the CPU of the hardware being used and the instructions written in the
programs were just like the instructions given in natural languages. The third generation
languages are known as 3GL languages.The current generation of the programming languages
are called the fourth generation languages or the 4GLs. These languages represent the class of
programming languages that are closest to the human (natural) languages. Based on the intended
use of domain of use, the programming languages are broadly classified as imperative
programming languages where imperative sentences are used in a program to issue commands in
terms of instructions; and declarative programming languages where declarative instructions are
used in a program to assert the desired result. But a more common paradigm classifies these
languages into imperative, functional, logic programming and object-oriented languages.

Following Table presents the summary of main features of these programming paradigms.

Paradigm Key Concepts Key Concepts Program Result


Execution

Functional Function Collection of Evaluation of Value of the


functions functions main function

Imperative Command Sequence of Execution of Final state of


(instruction) commands commands computer
memory

Logic Predicate Logic formulas: Logic proving of Failure or


axioms & a the theorem Success of
theorem proving

Object-oriented Object Collection of Exchange of Final state of the


classes of objects messages objects
between the
objects

1.2 PROCEDURE ORIENTED PROGRAMMING


____________________________________________________________________________________________
Conventional programming language using high level language such as Cobol and C, is
commonly known as Procedure Oriented Programming (POP). In Procedure Oriented
Programming, the problem is viewed as a sequence of a thing to be done. A number of functions
are written to accomplish his task. The primary focus is on functions. Procedure Oriented
Programming basically consists of writing a list of instructions for the computer to follow, and
organizing these functions into groups known as functions.In a multi-function program, many
important data items are placed as global so that they may be accessed by all the functions.
Each function may have its own local data. Global data are more vulnerable to an inadvertent
change by a function. In a large program it is very difficult to identify what data is used by which
function. Another serious drawback with the procedural approach is that it does not model real
world problems very well. This is because functions are action-oriented and do not really
corresponding to the elements of the problem.

Some characteristics of Procedure Oriented Programming are:

1. Large programs are divided into smaller programs known as functions.


2. Most of the functions share global data.
3. Data move openly around the system from function to function.
4. Functions transform data from one form to another.
5. Employs top-down approach in program design.

1.3 NEED OF OBJECT ORIENTED PROGRAMMING


____________________________________________________________________________________________
Developments in software technology continue to be dynamic.New tools and techniques are
announced in quick succession. This has forced the software engineers and industry to continuously
look for new approaches to software design and development, and they are becoming more and more
critical in view of the increasing complexity of software system as well as the highly competitive
nature of the industry. This rapid advance appears to have created a situation of crises within the
industry. The following issues needs to be solved:

 To represent real life entities of problems in system design.


 To design system with open interface.
 To ensure reusability and extensibility of modules.
 To develop modules that is tolerant to any changes in future
 To improve software productivity and decrease cost.
 To improve the quality of the software.
 To manage time schedule.
 To industrialize the software development process.
To overcome these problems and major motivation factor in the invention of object oriented
approach is to remove some of the flows encountered in the procedure oriented approach.

1.4 OBJECT ORIENTED PROGRAMMING


___________________________________________________________________________________________
Object Oriented Programming is the most recent concept among programming model. The
motivating factor in the invention of object oriented approach is to remove some of the flows
encountered in the procedural approach. OOPS treats data as a critical element in the program
development and does not allow it to flow freely around the system. It binds data more closely to
the functions that operate on it, and protects it from accidental modification from outside
functions.

Some of the striking features of Object Oriented Programming are:

 Importance on data rather than procedure.


 Programs are divided into what are known as objects.
 Data structures are designed as such that they characterize the objects.

Introduction to OOPs

 Functions that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follow bottom-up approach in program design.

1.5 COMPARISON OF PROCEDURAL AND OBJECT ORIENTED


APPROACH
____________________________________________________________________________________________

There are two different approaches to write a program, i.e., Procedure Oriented Programming
and Object Oriented Programming. Basic aim of these methods is nothing but to make
programming efficient. We can write the program using any of the way but there are notable
differences between both approaches.

Sr.No Procedure Oriented Programming Object Oriented Programming


1 POP is divided into small parts called as In OOP, program is divided into parts
functions called objects
2 In POP, Importance is not given to data In OOP, Importance is given to the data
but rather than procedures or functions because
to functions as well as sequence of it works as a real world.
actions to be done.
3 POP follows top-down approach. OOP follows bottom-up approach.
4 POP does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
5 In POP, data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
6 To add new data and function in POP is OOP provides an easy way to add new data
not so easy. and function.
7 In POP, most function uses global data In OOP, data cannot move easily from
for sharing that can be accessed freely function to function, it can be kept public or
from function to function in the system. private so we can control the access of data.
8 POP does not have any proper way for OOP provides data hiding so provides
hiding data so it is less secure. more security.
9 In POP, overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
10 Example of POP are: C, VB, FORTRAN, Example of OOP are: C++, JAVA,
Pascal. VB.NET, C#.NET.

1.6 BENEFITS OF OOP


____________________________________________________________________________________________

1) As OOP is closer to the real world phenomena, hence, it is easier to map real world problems
onto a solution in OOP.
2) The objects in OOP have the state and behaviour that is similar to the real world objects.
3) It is more suitable for large projects.
4) The projects executed using OOP techniques are more reliable.
5) It provides the bases for increased testability (automated testing) and hence higher quality.
6) Abstraction techniques are used to hide the unnecessary details and focus is only on the
relevant part of the problem and solution.
7) Encapsulation helps in concentrating the structure as well as the behaviour of various objects
in OOP in a single enclosure.
8) The enclosure is also used to hide the information and to allow strictly controlled access to the
structure as well as the behaviour of the objects.
9) OOP divides the problems into collection of objects to provide services for solving a
particular problem.
10) Object oriented systems are easier to upgrade/modify.
11) The concepts like inheritance and polymorphism provide the extensibility of the OOP
languages.
12) The concepts of OOP also enhance the reusability of the code written.
13) Software complexity can be better managed.
14) The use of the concept of message passing for communication among the objects makes the
interface description with external system much simpler.
15) The maintainability of the programs or the software is increased manifold. If designed
correctly, any tier of the application can be replaced by another provided the replaced tier
implements the correct interface(s). The application will still work properly.
1.7 ADVANTAGES OF OOPs
____________________________________________________________________________________________

1. Code reusability in terms of inheritance.


2. Object-oriented system can be easily upgraded from one platform to another.
3. Complex projects can be easily divided into small code functions.
4. The principle of abstraction and encapsulation enables a programmer to build secure
programs.
5. Software complexity decreases.
6. Principle of data hiding helps programmer to design and develop safe programs.
7. Rapid development of software can be done is short span of time.
8. More than one instance of same class can exist together without any interference.

1.8 OBJECT-ORIENTED LANGUAGES


____________________________________________________________________________________________

Some of the most popular Object-oriented Programming languages are :


a) C++
b) Ruby
c) Java.
d) Delphi
e) smalltalk
f) Charm++
g) Eiffle.
h) Simula.

1.9 APPLICATIONS OF OOPS


____________________________________________________________________________________________

Object concept helps to translate our thoughts to a program. It provides a way of solving a
problem in the same way as a human being perceives a real world problem and finds out the
solution. It is possible to construct large reusable components using object-oriented techniques.
Development of reusable components is rapidly growing in commercial software industries. If
there is complexity in software development, object-oriented programming is the best
paradigm to solve the problem. The following areas make the use of OOP:

1. Image Processing
2. Pattern Recognition
3. Computer Assisted Concurrent Engineering
4. Computer Aided Design and Manufacturing
5. Computer Aided Teaching
6. Intelligent Systems
7. Database Management Systems
8. Web-based Applications
9. Distributed Computing and Applications
10. Component-based Applications
11. Business Process Re-engineering
12. Enterprise Resource Planning
13. Data security and management
14. Mobile Computing
15. Data Warehouse and Data Mining
16. Parallel Computing

Q1. Why does hardware not provide flexibility of operations to the user ?

Q2. How is a program related to software?

Q3. What is the signature of a method?

Q4. Differentiate between information hiding and encapsulation.

Q5. What is the difference between object-oriented and object-based programming languages?

Q6. What is the NEED OF OBJECT ORIENTED PROGRAMMING ?

Q7. Differentiate Procedure Oriented Programming & Object Oriented Programming

Q8. List and Explain BENEFITS OF OOP .

Q9. List and Explain APPLICATIONS OF OOPS


UNIT – I

CHAPTER – 02

Principles of OOPS
Chapter Structure :

2.0 OBJECT-ORIENTED PROGRAMMING PARADIGM

2.1 CHARACTERISTICS OF OOPS / Concepts of OOPS

2.0 OBJECT-ORIENTED PROGRAMMING PARADIGM


____________________________________________________________________________________________

Simula was the first programming language developed in the mid-1960s to support the object-
oriented programming paradigm followed by Smalltalk in the mid-1970s that is known to be the
first ‘pure’ object-oriented language. Eiffel, Java, C++, Object Pascal, Visual Basic, C# etc are
the other OOP languages that came into existence later on, all having different complexities of
syntax and dynamic semantics.

The main motive of the developers of programming languages over the years has always been to
create such programming languages that are close to human (i.e. natural) languages. The way we
perceive and interact with the things in our day-to-day lives, the representation of programming
constructs should closely match the same. Hence came into existence the concept of ‘objects’
and ‘object-oriented programming paradigm’. Every object has certain defining properties which
distinguish it not only from different types of other objects but from the similar types of objects
too. If we take an example of an object like a ball pen, its defining property may be the colour in
which it can write, length, shape, unique manufacturing code etc. Some of these properties not
only distinguish the ball pen object from the tooth brush object but also distinguish individual
ball pens objects. It must be understood clearly that no two objects in the physical world, even of
same type, are identical since no two objects can have the value of all its defining properties
same. Likewise, every object has certain functions associated with it and all similar types of
objects are supposed to support these. Although, Some of these functions can be the same as
associated with different types of objects. In case of a ball pen, one of the functions associated
with each type of ball pen object, is to write and another associated function is the provision to
hold it in hands conveniently. All the ball pen objects support both these functions. Incidentally,
all the tooth brush objects also support the function of holding them in the hands conveniently
but, in addition, support other functions like brushing the teeth too.
This concept of objects borrowed from the real world has been the basis of the object-oriented
programming (OOP) paradigm and this paradigm is a direct consequence of an effort to have a
programming language closely matching the human behaviour. This OOP paradigm is all about
creating program(s) dealing with objects where these objects interact with one another to achieve
the overall objectives of the program. Every object in the programs has certain defining
properties called attributes (or instance variables) possessing supporting values for each of the
attributes and some associated functions (normally called methods or operations). As in the real
world objects, no two objects in a program can have the same values of all the attributes.
At times, instead of dealing with individual objects, it is convenient to talk collectively about a
group of similar objects where all the objects of this group will have the same set of attributes
and methods. In the object-oriented programming paradigm parlance, this collection of objects
corresponding to a particular group is known as a class. All programs under this paradigm
contain a description of the structure (corresponding to attributes) and behaviour (corresponding
to methods) of so called classes. In a program, various objects are created from these classes.
The process of creation of an object from a class is called ‘instantiation’ and the object created is
known as an instance of the class. Every object created will have a ‘state’ associated with the
description of the structure in the class from which it has been instantiated. The state of an object
is defined by the set of values assigned to its corresponding attributes (and stored in the memory)
of the object. Therefore, we can say that a class is used to represent a set of objects having same
structure and behaviour. So, how do we define a class? A class is defined to be a template or a
prototype so that a collection of attributes and methods can be described within it and this
definition can be used for creating different objects within a program. It is this concept of
encapsulating the data and methods within the objects that provides the programmers with
flexibility within the OOP paradigm because an object can be extended or modified without
making changes to its external interface or other classes/objects in the program. Various classes
may exhibit features like inheritance and polymorphism of methods.

When a program is executed, various objects are created with their corresponding states and
these objects interact with one another by exchanging messages, the messages thereby causing
the modification of their states. Modification in the state of an object is said to have occurred
when the values of one or more of its attributes (instance variables) change due to the interaction.
All the objects created are made to exhibit a behaviour through their corresponding methods such
that the program produces the desired results once its execution is over. A program in this
paradigm therefore, becomes a collection of cooperating and interacting objects instead of just a
list of objects. For the sake of an example, a Maruti Wagon-R could be an object. It would have a
state depend upon whether its engine is running or not. Also it would have a behaviour, like
starting ignition of its engine or stopping the ignition of its engine and this behaviour is
responsible for changing its state from ‘engine is not running’ to ‘engine is running’ or from
‘engine is running’ to ‘engine is not running’. In a different example, we can take object ABC
representing a student having a state defined by its attribute named RESULT. A part of the
behaviour of this object could be reflected through ‘compute result’. If this student has not
appeared in the examination yet, the state of this object defined by the attribute RESULT may be
NOT DECLARED. But once this student has appeared in the examination and the marks
obtained by this student are available, the behaviour of this object changes the state of the object
ABC by using the method ‘compute result’ from NOT DECLARED to either FAIL or PASS
with percentage of marks.

2.1 CHARACTERISTICS OF OOPS / Concepts of OOPS


____________________________________________________________________________________________
Characteristics of OOPs are :

 Object
 Classes
 Polymorphism
 Inheritance
 Reusability
 Data abstraction and encapsulation

Class

A group of objects that share common properties for data part and some program part are
collectively called as class. In C ++ a class is a new data type that contains member variables and
member functions that operate on the variables.

The most remarkable feature of C + + is a class. The class binds together data and methods
which work on data. The class is an abstract data type (ADI) so creation of class simply creates
a template. The general syntax of creating a class in C++ is given below:

class class name


{
public :
data & function;
private :
data & function;
protected :
data & function;
};

The class is a keyword. Following this keyword class, class_name represents name of the
class. The class name must obey rules of writing identifier as class_name is nothing but an
identifier. The class is opened by opening brace} and closed by closing brace}. The class
definition/declaration must end with semicolon. Inside the class we define the data members
and member functions. They may be defined either public, private or jn protected mode. There
are three different types of mode :

1. public
2. private
3. protected.

Object

Objects are the basic run time entities in an Object Oriented System. They may represent a
person, a bank account, a table of data or any item that the program has to handle. They may also
represent user-defined data such as vector, time, and lists. When a program is executed, the
objects interact by sending messages to one another. Creating objects is similar to declaring
variables.
Syntax:

<Class Name> <Object Name>;

For Example:

Student s1;
Where Student is a class name and s1 is its object.

Polymorphism

Poly means many. Morphism means forms. Polymorphism feature enables classes to provide
different implementation of methods having the same name.
There are two types of polymorphism:
1. Compile time (Overloading)
2. Run time (Overriding)

Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. The existing class is called as
base class and a new class which is created on the basis of base class is called as derived class.
There are 5 different types of inheritance, i.e.:
 Single level
 Multilevel
 Multiple
 Hierarchical
 Hybrid

Reusability

The concept of inheritance provides an important feature to the object-oriented


languagereusability. A programmer can take an existing class and, without modifying it, and
additional features and capabilities to it. This is done by deriving a new class from an existing
class.

Data Abstraction and Encapsulation

 The wrapping up of data and functions into a single unit is known as encapsulation.
 Data encapsulation is the most striking feature of a class.
 Abstraction refers to the act of representing essential features without including the
background details or explanations.
 Encapsulation is the hiding of information in order to ensure that data structures and
operators are used as intended and to make the usage model more obvious to the
developer.
 C++ provides the ability to define classes and functions as its primary encapsulation
mechanisms.

Dynamic Binding

Binding means linking. It is linking of function definition to a function call.


1. If linking of function call to function definition i.e., a place where control has to be transferred
is done at compile time, it is known as static binding.
2. When linking is delayed till run time or done during the execution of the program then this
type of linking is known as dynamic binding. Which function will be called in response to a
function call is find out when program executes.

Message Passing

In C++ objects communicate each other by passing messages to each other. A message contains
the name of the member function and arguments to pass. In message passing shown below :
object. method (parameters);
Message passing here means object calling the method and passing parameters. Message
passing is nothing but the calling the method of the class and sending parameters. The method
is turn executes in response to a message.

Q1. Discuss programming paradigms in detail.

Q2. Explain Characteristics of OOPs

Q3. What is class and Objects ? Explain with example.

Q4. Explain the terms a) Dynamic Binding b) Message Passing


UNIT – II

CHAPTER – 03

Classes and Objects


Chapter Structure :

3.0 BASICS OF C++

3.0.0 C++ Character Set

3.0.1 White Spaces Characters

3.0.2 Tokens:

3.0.3 Identifiers

3.0.4 Keywords

3.0.5 SIMPLE C++ PROGRAMS

3.0.6 DIFFERENCE BETWEEN C AND C++

3.0.7 DATA TYPES IN C++

3.0.8 VARIABLES

3.0.9 LITERALS OR CONSTANTS

3.0.10 OPERATORS IN C++

3.0.11 CONTROL STRUCTURE IN C++

3.0.12 Iterative or looping statement

3.0.13 Breaking statement

3.1 C++ Classes and Objects

3.2 C++ Class Definitions

3.3 Define C++ Objects

3.4 Accessing the Data Members

3.5 Classes and Objects in Detail

3.6 Defining Class and Declaring Objects


3.7 Declaring Objects

3.8 Accessing data members and member functions

3.9 Member Functions in Classes

3.10 Passing and Returning Objects in C++

3.11 Returning Object (method) as argument

3.12 FRIEND FUNCTION

3.13 Pointer to C++ Classes

3.14 C++ Array of Pointers

3.0 BASICS OF C++


______________________________________________________________________________________________
C++ is an object oriented programming (OOP) language. It was developed at AT&T Bell
Laboratories in the early 1979s by Bjarne Stroustrup. Its initial name was C with classes, but later on
in 1983 it was renamed as C++. It is a deviation from traditional procedural languages in the sense
that it follows object oriented programming (OOP) approach which is quite suitable for managing
large and complex programs. C++ language is an extension to C language and supports classes,
inheritance, function overloading and operator overloading which were not supported by C language.
In any language, there are some fundamentals you need to learn before you begin to write even the
most elementary programs. This chapter includes these fundamentals; basic program constraints,
variables, and Input/output formats. C++ is a superset of C language. It contains the syntax and
features of C language. It contains the same control statements; the same scope and storage class
rules; and even the arithmetic, logical, bitwise operators and the data types are identical. C and C++
both the languages start with main function. The object oriented feature in C++ is helpful in
developing the large programs with clarity, extensibility and easy to maintain the software after sale
to customers. It is helpful to map the real-world problem properly. C++ has replaced C programming
language and is the basic building block of current programming languages such as Java, C# and
Dot.Net etc.

3.0.0 C++ Character Set


______________________________________________________________________________________________
Character set is a set of valid characters that a language can recognise. The character set of C++ is
consisting of letters, digits, and special characters.
The C++ has the following character set:

Letters (Alphabets) A-Z, a-z

Digits 0-9

Special Characters #, <=, >=, @ ,+, -, *, /, ^, \, ( ), [ ], { }, =, !, <


>. „, ", $, ;, :, % , &, ?, _
There are 62 letters and digits character set in C++ (26 Capital Letters + 26 Small Letters + 10
Digits) as shown above. Further, C++ is a case sensitive language, i.e. the letter A and a, are distinct
in C++ object oriented programming language. There are 29, punctuation and special character set in
C++ and is used for various purposes during programming.

3.0.1 White Spaces Characters


______________________________________________________________________________________________

A character that is used to produce blank space when printed in C++ is called white space character.
These are spaces, tabs, new-lines, and comments.

3.0.2 Tokens:
______________________________________________________________________________________________
A token is a group of characters that logically combine together. The programmer can write a
program by using tokens. C++ uses the following types of tokens:

 Keywords
 Identifiers
 Literals
 Punctuators
 Operators

3.0.3 Identifiers
______________________________________________________________________________________________
A symbolic name is generally known as an identifier. Valid identifiers are a sequence of one or more
letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier. Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter. In no case can they begin with a digit. Another
rule for declaring identifiers is that they cannot match any keyword of the C++ programming
language. The rules for the formation of identifiers can be summarised as:
A symbolic name is generally known as an identifier. Valid identifiers are a sequence of one or more
letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier. Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter. In no case can they begin with a digit. Another
rule for declaring identifiers is that they cannot match any keyword of the C++ programming
language. The rules for the formation of identifiers can be summarised as:

3.0.4 Keywords
______________________________________________________________________________________________
There are some reserved words in C++ which have predefined meaning to complier called keywords.
These are also known as reserved words and are always written or typed in lower cases. There are
following keywords in C++ object oriented language:
List of Keywords:

asm case class void


double extern friend default
new protected return inline
switch try unsigned sizeof
auto catch const volatile
else float goto delete
operator public short int
template typedef virtual static
break char continue while
enum for if do
private register signed long
this union struct

3.0.5 SIMPLE C++ PROGRAMS


______________________________________________________________________________________________

1)
#include <iostream.h> // Section: 1- The include Directive
int main () // Section: 3 - Main function definition
{ // Section: 4 - Declaration of an object
cout << "Hello World!";
return 0;
}

2)
#include <iostream.h>
# include<conio.h>
main()
{
char name [15];
clrscr();
cout << "Enter your name:”;
cin >> name;
cout<<”Your name is: “ <<name;
return0;
}

3)
#include <iostream.h>
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}

3.0.6 DIFFERENCE BETWEEN C AND C++


______________________________________________________________________________________________

Following are some differences between C and C ++ :


termediate-level language. It comprises a combination of both high-level
and low-level language features. C++ is an extension to C Programming language. The difference
between the two languages can be summarised as follows:

C, must occur at the top of the function block and it must be declared
before any executable statement. In C++ variables can be declared anywhere in the program.

no such
facility in C language.

-down approach while C++ follows both top-down and bottom-up


design approach.

identifier name whereas C++ allows no limit on


identifier length.

allow this feature.

3.0.7 DATA TYPES IN C++


______________________________________________________________________________________________
C++ defines several data types which can be used under different programming situations like
an int data type can be used to represent whole numbers as age of a person, roll number etc.
or float data type can be used to represent salary of person, interest rate etc. The basic data
types are as shown as follows :

1. Built-in Type

(a) Integral Type


(i) int
(ii) char
(b) Floating Types
(i) float
(ii) double
(c) void
(d) bool
(e) wchar_

2. User Defined Data Type

(a) class
(b) struct
(c) union
(d) enumeration

3. Derived Data Types

(a) array
(b) function
(c) pointer
(d) reference

3.0.8 VARIABLES
______________________________________________________________________________________________
A variable is a named location in memory that is used to hold a value that can be modified
in the program by the instruction. All variables must be declared before they can be used. They
must be declared in the beginning of the function or block (except the global variables). The
general form of variable declaration is :

data type variable [list];

Here list denotes more than one variable separated by commas;

Example :

int a;
float b,c;
char p,q;

Here a is a variable of type int, b and c are variable of type float, and p, q are variables
of type char, int, float and char are data types used in C. The rule for writing variables are same
as for writing identifiers as a variables is nothing but an identifier.
C++ allows you to declare variables anywhere in the program. That is unlike C it is not
necessary to declare all the variables in the beginning of the program. You can declare wherever
you want it to be declares i.e., right on the place where you want to use it. An advantage of
this is that sometimes lots of variables are declared in the advance in the beginning of the
program and many of them are unreferenced. Declaring variables at the place where they are
actually required is handy. You do not need to declare all the variables earlier prior to their use.
On the other hand, it is burdensome to look for all the variable declared in the program as
variable declaration will be scattered everywhere in the whole program.
C++ also allows you to initialize variable dynamically at the place of use. That is you can
write anywhere in the program like this.

int x = 23;
float sal = 2345;
char name[ ] = “Hari”;
This is known as “Dynamic Initialization” of the variables.

3.0.9 LITERALS OR CONSTANTS


______________________________________________________________________________________________
A number which does not charge its value during execution of a program is known as a constant or
literals. Any attempt to change the value of a constant will result in an error message. A keyword
const is added to the declaration of an identifier to make that identifier constant. A constant in C++
can be of any of the basic data types. Let us consider the following C++ expression:

const float Pi = 3.1215;

The above declaration means that Pi is a constant of float types having a value: 3.1415.

Examples of some valid constant declarations are:


const int rate = 50;
const float Pi = 3.1415;
const char ch = „A‟;

3.0.10 OPERATORS IN C++


______________________________________________________________________________________________
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
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators
one by one.

Arithmetic Operators
There are following arithmetic operators supported by C++ language −
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 the A - B will give -10


first
* Multiplies both operands A * B will give 200

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

% Modulus Operator and remainder of B % A will give 0


after an integer division

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


value by one

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


integer value by one

Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

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


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

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


are equal or not, if values are not
equal then condition becomes true.

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


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

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


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

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


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

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


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

Logical Operators
There are following logical operators supported by C++ language.
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.

Bitwise Operators
Bitwise operator works on bits and perform 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
The Bitwise operators supported by C++ language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then −

Operator Description Example

& Binary AND Operator copies a


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

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


bit if it exists in either is 0011 1101
operand.

^ Binary XOR Operator copies


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

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


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

<< Binary Left Shift Operator.


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

>> Binary Right Shift Operator.


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

Assignment Operators
There are following assignment operators supported by C++ language −

Operator Description Example


= Simple assignment operator,
C = A + B will assign
Assigns values from right side
value of A + B into C
operands to left side operand.

+= Add AND assignment


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

-= Subtract AND assignment


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

*= Multiply AND assignment


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

/= Divide AND assignment


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

%= Modulus AND assignment


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

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


operator. << 2

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


operator. >> 2

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


operator. &2

^= Bitwise exclusive OR and C ^= 2 is same as C = C ^


assignment operator. 2
|= Bitwise inclusive OR and C |= 2 is same as C = C |
assignment operator. 2

Misc Operators
The following table lists some other operators that C++ supports.

Sr.No Operator & Description

1
sizeof
sizeof 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.

3.0.11 CONTROL STRUCTURE IN C++


______________________________________________________________________________________________
C++ program is usually not limited to a linear sequence of instructions but it may bifurcate, repeat
code or may have to take decisions during the process of coding. For that purpose, C++ provides
control structures which are used to control the flow of program. Before we discuss control
structures, let us first discuss a new concept: the compound-statement or block, which is very much
needed to understand well the flow of control in a program. A block is a group of statements which
are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in
braces: { }: for example: { statement1; statement2; statement3; ... } represents a compound statement
or block. In C++ object oriented programming, the control structure can be classified into following
three categories: Selection or conditional statement; Iterating or looping statement; Breaking
statement; Let us discuss the above control statement and their types in the following section.

Selection or conditional statement

In this type of statement, the execution of a block depends on the next condition. If the condition
evaluates to true, then one set of statement is executed, otherwise another set of statements is
executed. C++ provides following types of selection statements: If; If-else; Nested if; Switch
conditional

a) if statement:

The syntax of if statement is

If (expression)
{
(Body of if)
Statements;
}

Where, expression is the condition that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after this
conditional structure.

# include <iostream.h>
main()
{ int a, b;
a=10;
b=20;
if (a<b)
cout <<”a is less than b”;
}

Output: a is less than b.

b) if-else statement:

The syntax of if –else statement is

If (expression)
{
(Body of if)
Statements 1;
}
else
{
(Body of else}
Statement 2
}

# include <iostream.h>
main()
{ int a, b;
a=10;
b=20;
if (a<b)
cout <<”a is less than b”;
}
else
{
cout<< “b is less than a”
}

Output: a is less than b.

c) Switch statement:

Switch statement is used for multiple branch selection. The syntax of switch statement is

switch (expression)
{
case exp 1:
First case body;
Break;
case exp 2:
Second case body;
Break;
case exp 3:
Third case body;
Break;
default:
default case body;
}
# include <iostream.h>
# include <conio.h>
int main()
{
clrscr();
int d_o_w;
cout <<”Enter number of week‟s day (1-7)”;
cin>>d_o_w;
switch(d_o_w)
{
case 1: cout<<”/n Sunday”;
break;
case 2: cout<<”/n Monday”;
break;
case 3: cout<<”/n Tuesday”;
break;
case 4: cout<<”/n Wednesday”;
break;
case 5: cout<<”/n Thursday”;
break;
case 6: cout<<”/n Friday”;
break;
case 7: cout<<”/n Saturday”;
break;
default: cout<<”/n Wrong number of day”;
}
return 0;
}

Output:
Enter number of week‟s dat (1-7):
7
Saturday

3.0.12 Iterative or looping statement


______________________________________________________________________________________________
In C++ , programming language looping statement is used to repeat a set of instructions until certain
condition is fulfilled. The iteration statements are also called loops or looping statement. C++ allows
following four kinds of iterative loops:
 for loop
 while loop
 do-while loop and
 nested loops

This loop is specially designed to perform a repetitive action with a counter which is initialized and
increased on each iteration
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "****!\n";
return 0;
}

Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ****!


// Program by using while loop
#include <iostream.h>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number : ";
cin >> n;
while (n>0)
{
cout << n << ", ";
-n;
}
cout << "****!\n";
return 0;
}

Enter the starting number: 8


8, 7, 6, 5, 4, 3, 2, 1, ****!

#include <iostream.h>
using namespace std;
int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
return 0;
}

Output: Enter number (0 to end): 12345


You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0

3.0.13 Breaking statement


______________________________________________________________________________________________
Using break, we can leave a loop even if the condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its natural end. In this section, we will discuss
following breaking statements:

 break statement
 continue statement
 goto statement and
 exit statement

// break loop example


#include <iostream.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}

Output:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

// continue loop example


#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "****!\n";
return 0;
}
Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, ****!
// goto loop example
#include <iostream.h>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "****!\n";
return 0;
}

Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, ****!

// Program for exit statement


#include <iostream.h>
#include <conio.h>
void main ()
{
clrscr();
int i, number;
i = 1;
while(i<5)
{
cout <<”Enter the number:";
cin>>number;
if number>5
{
cout <<”The number is greater than five or equal to” <<end1;
exit();
}
cout << "The number is: “<<number<<end1;
i++
}
getch();
}

Output:
Enter the number: 2
The number is: 2
Enter the number: 3
The number is: 3
Enter the number: 9
The number is greater than or equal to 9
3.1 C++ Classes and Objects
______________________________________________________________________________________________
The main purpose of C++ programming is to add object orientation to the C programming language and
classes are the central feature of C++ that supports object-oriented programming and are often called user-
defined types.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called members of the
class.

3.2 C++ Class Definitions


______________________________________________________________________________________________
When we define a class, we define a blueprint for a data type. This doesn't actually define any data, but it does
define what the class name means, that is, what an object of the class will consist of and what operations can
be performed on such an object.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a
pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For
example, we defined the Box data type using the keyword class as follows −

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The keyword public determines the access attributes of the members of the class that follows it. A public
member can be accessed from outside the class anywhere within the scope of the class object. You can also
specify the members of a class as private or protected which we will discuss in a sub-section.

3.3 Define C++ Objects


______________________________________________________________________________________________
A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of
a class with exactly the same sort of declaration that we declare variables of basic types. Following statements
declare two objects of class Box −
Box Box12; // Declare Box12 of type Box
Box Box11; // Declare Box11 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

3.4 Accessing the Data Members


______________________________________________________________________________________________
The public data members of objects of a class can be accessed using the direct member access operator (.). Let
us try the following example to make the things clear −
#include <iostream.h>
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main()
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly using direct member
access operator (.). We will learn how private and protected members can be accessed.

3.5 Classes and Objects in Detail


______________________________________________________________________________________________
So far, you have got very basic idea about C++ Classes and Objects. There are further interesting concepts
related to C++ Classes and Objects which we will discuss in various sub-sections listed below −

Concept & Description

Class Member Functions


A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable.

Class Access Modifiers

A class member can be defined as public, private or protected. By default members would
be assumed as private.

Constructor & Destructor

A class constructor is a special function in a class that is called when a new object of the class
is created. A destructor is also a special function which is called when created object is deleted.

Copy Constructor

The copy constructor is a constructor which creates an object by initializing it with an object
of the same class, which has been created previously.

Friend Functions

A friend function is permitted full access to private and protected members of a class.

Inline Functions

With an inline function, the compiler tries to expand the code in the body of the function in
place of a call to the function.

this Pointer

Every object has a special pointer this which points to the object itself.

Pointer to C++ Classes

A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class
is really just a structure with functions in it.

Static Members of a Class

Both data members and function members of a class can be declared as static.

3.6 Defining Class and Declaring Objects


______________________________________________________________________________________________
A class is defined in C++ using keyword class followed by the name of class. The body of class is
defined inside the curly brackets and terminated by a semicolon at the end.

3.7 Declaring Objects


______________________________________________________________________________________________
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:

ClassName ObjectName;

3.8 Accessing data members and member functions


______________________________________________________________________________________________

The data members and member functions of class can be accessed using the dot(„.‟) operator with
the object. For example if the name of object is obj and you want to access the member function
with the name printName() then you will have to write obj.printName() .

Accessing Data Members


The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member depends
solely on the access control of that data member.
This access control is given by Access modifiers in C++. There are three access modifiers : public,
private and protected.

Access-control specifiers Accessible to

Own class members Objects of a class

private yes no

protected yes no

public yes yes


A class can use all of three visibility/accessibility labels as illustrated below:
Class A
{
private:
int x;
void fun1()
{
// This function can refer to data members x, y, z and functions fun1(), fun2() and fun3()
}
protected:
int y;
void fun2()
{
//This function can also refer to data members x, y, z and functions fun1(), fun2() and fun3()
}
public :
int z;
void fun3()
{
//This function can also refer to data members x, y, z and functions fun1(), fun2() and fun3()
}
};
Now, consider the statements
A obja; //obja is an object of class A
int b; // b is an integer variable
The above statements define an object obja and an integer variable b. The accessibility of members of the
class A is illustrated through the obja as follows:
1. Accessing private members of the class A:
b=obja.x; //Won‟t Work: object can not access private data member „x‟
obja.fun1(); //Won‟t Work: object can not access private member function fun1()
Both the statements are illegal because the private members of the class are not accessible.

2. Accessing protected members of the class A:


b=obja.y; // Won‟t Work: object can not access protected data member „y‟
obja.fun2(); // Won‟t Work: object can not access member function fun2()
Both the statements are also illegal because the protected members of the class are not accessible.

3. Accessing public members of the class A:


b=obja.c; //OK
obja.fun3(); //OK
Both the statements are valid because the public members of the class are accessible.

3.9 Member Functions in Classes


______________________________________________________________________________________________
A member function performs an operation required by the class. It is the actual interface to initiate an action
of an object belonging to a class. It may be used to read, manipulate, or display the data member. The data
member of a class must be declared within the body of the class, while the member functions of a class can be
defined in two places:

 Inside class definition


 Outside class definition

The syntax of a member function definition changes depending on whether it is defined inside or outside the
class declaration/definition. However, irrespective of the location of their definition, the member function
must perform the same operation. Thus, the code inside the function body would be identical in both the
cases. The compiler treats these two definitions in a different manner. Let us see, how we can define the
member function inside the class definition.

The syntax for specifying a member function declaration is similar to a normal function definition except that
is enclosed within the body of a class. Foe example, we could define the class as follows:

class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<"\n Minimum value is ="<<min<<endl;
}
};

if you look at the above declaration of class number you can observe that the member function get_data() and
maiximun() are declared, but they are not defined. The only member function which is defined in the class
body is minimum(). When a function is defined inside a class, it is treated as a inline function. Thus, member
function minimum is a inline function. Generally, only small functions are defined inside the class.

Now let us see how we can define the function outside the class body. Member functions that are declared
inside a class have to be defined outside the class. Their definition is very much like the normal function. Can
you tell how does a compiler know to which class outside defined function belong? Yes, there should be a
mechanism of binding the functions to the class to which they belong. This is done by the scope resolution
operator (::). It acts as an identity-label. This label tells the compiler which class the function belongs to. The
common syntax for member function definition outside the class is as follows:
return_type class_name :: function_name(argument declaration)
{
functionbody
}
The scope resolution :: tells the compiler that the function_name belongs to the class class_name.
Let us again consider the class Number.
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration.
.
.
};
void Number :: get_data(void)
{
cout<< "\n Enter the value of fist number(x):"<<endl;
cin>>x;
cout<< "\n Enter the value of second number(y):"<<endl;
cin>>y;
cout<< "\n Enter the value of third number(z):"<<endl;
cin>>z;

}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<"\n Maximun value is ="<<max<<endl;
}

if you look at the above declaration of class Number, you can easily see that the member function get_data()
and maiximun() are declared in the class. Thus, it is necessary that you have to define this function. You can
also observe in the above snapshot of C++ program identity label (::) which are used in void Number ::
get_data(void) and void Number ::maximum(void) tell the compiler the functionget_data() and maximum()
belong to the class Number.

Now, let us see the complete C++ program to find out the minimum and maximum of three given integer
numbers:
#include<iostream.h>
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<"\n Minimum value is ="<<min<<endl;
}
};
void Number :: get_data(void)
{
cout<< "\n Enter the value of fist number(x):"<<endl;
cin>>x;
cout<< "\n Enter the value of second number(y):"<<endl;
cin>>y;
cout<< "\n Enter the value of third number(z):"<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<"\n Maximun value is ="<<max<<endl;
}
void main()
{
Number num;
num.get_data();
num.minimum();
num.maximum();
}

output:
Enter the value of the first number (x):
10
Enter the value of the second number (y):
20
Enter the value of the third number (z):
5
Minimum value is=5
Maximum value is=20

3.10 Passing and Returning Objects in C++


______________________________________________________________________________________________
In C++ we can pass class‟s objects as arguments and also return them from a function the same way we pass
and return other variables. No special keyword or header file is required to do so.

Passing an Object as argument

To pass an object as an argument we write the object name as the argument while calling the function the
same way we do it for other variables.

Syntax:

function_name(object_name);

Example: In this Example there is a class which has an integer variable „a‟ and a function „add‟ which takes
an object as argument. The function is called by one object and takes another as an argument. Inside the
function, the integer value of the argument object is added to that on which the „add‟ function is called. In this
method, we can pass objects as an argument and alter them.

// C++ program to show passing

// of objects to a function
#include<iostream.h>
class Example {
public:
int a;
// This function will take
// an object as an argument
void add(Example E)
{
a = a + E.a;
}
};
// Driver Code
int main()
{
// Create objects
Example E1, E2;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a << "\n\n";
// Passing object as an argument
// to function add()
E2.add(E1);
// Changed values after passing
// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
return 0;
}
Output:

Initial Values
Value of object 1: 50
& object 2: 100

New values
Value of object 1: 50
& object 2: 150

3.11 Returning Object (method) as argument


______________________________________________________________________________________________
Syntax:

object = return object_name;

Example: In the above example we can see that the add function does not return any value since its return-
type is void. In the following program the add function returns an object of type „Example'(i.e., class name)
whose value is stored in E3.
In this example, we can see both the things that are how we can pass the objects as well as return them. When
the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the
function, another object is declared which calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the add function returns
an object whose value is stored in another object of the same class „Example‟ E3. Here the value of E1 is
displayed by object1, the value of E2 by object2 and value of E3 by object3.

// C++ program to show passing


// of objects to a function
#include <iostream.h>
class Example {
public:
int a;
// This function will take
// object as arguments and
// return object
Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = 50;
Ec.a = Ec.a + Ea.a + Eb.a;
// returning the object
return Ec;
}
};
int main()
{
Example E1, E2, E3;
// Values are initialized
// for both objects
E1.a = 50;
E2.a = 100;
E3.a = 0;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a << "\n";
// Passing object as an argument
// to function add()
E3 = E3.add(E1, E2);
// Changed values after
// passing object as an argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a << ", \nobject 3: " << E3.a<< "\n";
return 0;
}

Output:

Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0

New values
Value of object 1: 50,
object 2: 100,
object 3: 200
3.12 FRIEND FUNCTION
______________________________________________________________________________________________
As we have discussed that the private members cannot be accessed from outside the class. It implies that a
non-member function cannot have an access to the private data of a class. Let us suppose, we want a function
operate on objects of two different classes. In such situations, C++ provides the friend function which is used
to access the private members of a class. Friend function is not a member of any class. So, it is defined
without scope resolution operator. The syntax of declaring friend function is given below:

class class_name
{


public:


friend return type function_name(arguments);
}

Let us consider the complete C++ program to find out sum of n given numbers to understand the concept of
friend function

#include<iostream.h>
#define MAX_SIZE 100
class Sum
{
int num[MAX_SIZE];
int n;
public:
void get_number(void);
friend int add(void);
};
void Sum :: get_number(void)
{
cout<< "\n Enter the total number(n):"<<endl;
cin>>n;
cout<< "\n Enter the number:"<<endl;
for (int i=0;i<n; i++)
cin>>num[i];
}
int add(void)
{
Sum s;
int temp=0;
s.get_number();
for (int i=0;i<s.n; i++)
temp+=s.num[i];
return temp;
}
void main()
{
int res;
res=add();
cout<<"The sum of n value is="<<res<<endl;
}

If you look at the above program, you can easily see that the function add is declared as a friend function of
class Sum. The add function accesses the private data, adds the numbers of array and returns value to the main
function where it is called upon. Furthermore, you can also see that friend function add() is defined without
scope resolution operator(::), because it does not belong to a class.

Now, let us consider a situation in which we want to operate on objects of two different classes. In such a
situation, friend functions can be used to bridge the two classes

#include<iostream.h>
class Two; //forward declaration like function prototype
class One
{
int a;
public:
void get_a(void);
friend int min(One, Two);
};
class Two
{
int b;
public:
void get_b(void);
friend int min(One, Two);
};
void One :: get_a(void)
{
cout<<"Enter the value of a:"<<endl;
cin>>a;
}
void Two :: get_b(void)
{
cout<<"Enter the value of b:"<<endl;
cin>>b;
}
int min (One o, Two t)
{
if(o.a<t.b)
return o.a;
else
return t.b;
}
void main()
{
One one;
Two two;
int minvalue;
one.get_a();
two.get_b();
minvalue=min(one,two);
cout<<"Minimum="<<minvalue<<endl;
}
You can observe that the above program contains two classes named one and two. The function min() is
declared in the both the classes with the keyword friend. An object of each class has been passed as an
argument to the function min (). Being a friend function, it can access the private members of both classes
through these arguments.

Now, let us note some special properties possessed by friend function:

(i) A friend function is not in the scope of the class to which it has been declared as friend.
(ii) A friend function cannot be called using the object of that class. It can be invoked like a normal function
without the use of any object.
(iii) Unlike member functions, it can not access the members directly. However, it can use the object and dot
membership operator with each member name to access both private and public members.
(iv) It can be declared either in the public or the private part of a class without affecting its meaning.
(v) Generally, it has got objects as arguments.

3.13 Pointer to C++ Classes


______________________________________________________________________________________________
A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a
pointer to a class you use the member access operator -> operator, just as you do with pointers to structures.
Also as with all pointers, you must initialize the pointer before using it.
Let us try the following example to understand the concept of pointer to a class –

#include <iostream.h>

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.
// Save the address of first object
ptrBox = &Box1;

// Now try to access a member using member access operator


cout << "Volume of Box1: " << ptrBox->Volume() << endl;

// Save the address of second object


ptrBox = &Box2;

// Now try to access a member using member access operator


cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;
}

Output :

Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102

3.14 C++ Array of Pointers


______________________________________________________________________________________________

Array and pointers are closely related to each other. In C++, the name of an array is considered às a pointer,
i.e., the name of an array contains the address of an element. C++ considers the array name as the address of
the first element. For example, if we create an array, i.e., marks which hold the 20 values of integer type, then
marks will contain the address of first element, i.e., marks[0]. Therefore, we can say that array name (marks)
is a pointer which is holding the address of the first element of an array.

Let's understand this scenario through an example.

1. #include <iostream.h>
2. int main()
3. {
4. int *ptr; // integer pointer declaration
5. int marks[10]; // marks array declaration
6. std::cout << "Enter the elements of an array :" << std::endl;
7. for(int i=0;i<10;i++)
8. {
9. cin>>marks[i];
10. }
11. ptr=marks; // both marks and ptr pointing to the same element..
12. std::cout << "The value of *ptr is :" <<*ptr<< std::endl;
13. std::cout << "The value of *marks is :" <<*marks<<std::endl;
14. }

In the above code, we declare an integer pointer and an array of integer type. We assign the address of marks
to the ptr by using the statement ptr=marks; it means that both the variables 'marks' and 'ptr' point to the same
element, i.e., marks[0]. When we try to print the values of *ptr and *marks, then it comes out to be same.
Hence, it is proved that the array name stores the address of the first element of an array.

Output :

Array of Pointers

An array of pointers is an array that consists of variables of pointer type, which means that the variable is a
pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers;
then its declaration would look like:

1. int *ptr[5]; // array of 5 integer pointer.

In the above declaration, we declare an array of pointer named as ptr, and it allocates 5 integer pointers in
memory.

The element of an array of a pointer can also be initialized by assigning the address of some other element.
Let's observe this case through an example.

1. int a; // variable declaration.


2. ptr[2] = &a;

In the above code, we are assigning the address of 'a' variable to the third element of an array 'ptr'.

We can also retrieve the value of 'a' be dereferencing the pointer.

1. *ptr[2];

Let's understand through an example.

1. #include <iostream.h>
2. int main()
3. {
4. int ptr1[5]; // integer array declaration
5. int *ptr2[5]; // integer array of pointer declaration
6. std::cout << "Enter five numbers :" << std::endl;
7. for(int i=0;i<5;i++)
8. {
9. std::cin >> ptr1[i];
10. }
11. for(int i=0;i<5;i++)
12. {
13. ptr2[i]=&ptr1[i];
14. }
15. // printing the values of ptr1 array
16. std::cout << "The values are" << std::endl;
17. for(int i=0;i<5;i++)
18. {
19. std::cout << *ptr2[i] << std::endl;
20. }
21. }

In the above code, we declare an array of integer type and an array of integer pointers. We have defined the
'for' loop, which iterates through the elements of an array 'ptr1', and on each iteration, the address of element
of ptr1 at index 'i' gets stored in the ptr2 at index 'i'.

Output :

Till now, we have learnt the array of pointers to an integer. Now, we will see how to create the array of
pointers to strings.

Array of Pointer to Strings

An array of pointer to strings is an array of character pointers that holds the address of the first character of a
string or we can say the base address of a string.

The following are the differences between an array of pointers to string and two-dimensional array of
characters:
o An array of pointers to string is more efficient than the two-dimensional array of characters in case of memory
consumption because an array of pointer to strings consumes less memory than the two-dimensional array of
characters to store the strings.
o In an array of pointers, the manipulation of strings is comparatively easier than in the case of 2d array. We can
also easily change the position of the strings by using the pointers.

Let's see how to declare the array of pointers to string.

First, we declare the array of pointer to string:

1. char *names[5] = {"john",


2. "Peter",
3. "Marco",
4. "Devin",
5. "Ronan"};

In the above code, we declared an array of pointer names as 'names' of size 5. In the above case, we have done
the initialization at the time of declaration, so we do not need to mention the size of the array of a pointer. The
above code can be re-written as:

1. char *names[ ] = {"john",


2. "Peter",
3. "Marco",
4. "Devin",
5. "Ronan"};

In the above case, each element of the 'names' array is a string literal, and each string literal would hold the
base address of the first character of a string. For example, names[0] contains the base address of "john",
names[1] contains the base address of "Peter", and so on. It is not guaranteed that all the string literals will be
stored in the contiguous memory location, but the characters of a string literal are stored in a contiguous
memory location.

Let's create a simple example.

1. #include <iostream.h>
2. int main()
3. {
4. char *names[5] = {"john",
5. "Peter",
6. "Marco",
7. "Devin",
8. "Ronan"};
9. for(int i=0;i<5;i++)
10. {
11. std::cout << names[i] << std::endl;
12. }
13. return 0;
14. }

In the above code, we have declared an array of char pointer holding 5 string literals, and the first character of
each string is holding the base address of the string.
Output :

___________________________________________________________________________________Q1.
Q1. Write a C+ + program to find out the sum of n numbers.

Q2. What are classes? Explain purpose of classes?

Q3. Explain the term control structure in C++?

Q4. Explain the function of operators in C++?

Q5. What do you mean by keyword in C++?

Q6. What do you mean by identifier in C++?

Q7. What do you mean by data types in C++?

Q8. What is the difference between variable and constant in C++ programming language?

Q9. What do you mean by global variable and local variable in C++?

Q10. Explain the difference between C and C++?

Q11. What is the scope resolution operator?

Q12. What is the purpose of the member function?

Q13. What is friend class? Write a program to illustrate the concept of friend class.

Q14. Why is friend function needed?


UNIT – II

CHAPTER – 04

Constructors and Destructors


Chapter Structure :

4.1 C++ Class Constructor and Destructor

4.2 features of the constructor

4.3 CONSTRUCTOR WITH PARAMETERS

4.4 DESTRUCTOR

4.5 Features of Destructor

4.1 C++ Class Constructor and Destructor


______________________________________________________________________________________________
constructor is a special member function whose name is same as the name of its class in
which it is declared and defined. The purpose of the constructor is to initialize the objects of
the class. The constructor is called so because it is used to construct the objects of the class.

example of constructor and later illustrate its various features :

#include < iostream.h >


#include < conio.h >
class demo
{
public:
demo()
{
cout< <"Hello from constructor \n";
}
};
void main()
}
clrscr( );
demo d;
getch( );

OUTPUT :

Hello from constructor

4.2 features of the constructor


______________________________________________________________________________________________

1. The constructors are always declared in the public section. If declared in the private section then
objects are can only be created inside the member functions but serve no purpose.
2. They are invoked automatically when objects of the class are created. The declaration demo d;
creates an object d which automatically calls the constructor of the class and prints Hello from
constructor.
3. They do not have any return type not even void so they cannot return any value.
4. Constructors cannot be inherited, but they can be called from the constructors of derived
class.
5. Constructors are used to construct the object of the class.
6. The constructor with no argument is known as default constructor of the class. The default
constructor for the class demo will be demo : demo( )
7. Constructors which take arguments like a function takes are known as parameterized
constructor.
8. There is no limit of the number of constructors declared in a class but they all must
conform to rules of function overloading.
9. Constructor can have default arguments.
10. Addresses of constructors cannot be taken.
11. Constructors cannot be virtual.
12. Constructor make implicit calls to operators new and delete in case memory allocation and
de- allocation is to be performed.

4.3 CONSTRUCTOR WITH PARAMETERS


______________________________________________________________________________________________
Constructor are similar to functions but they have the name as class name so similar to functions
which takes argument we can have constructor which can take arguments. The constructor which
takes parameters is known as parameterized constructor. Again depending upon type of arguments
and number of arguments they may be overloaded. An example of this is given below:

#include <iostream.h>
#include <conio.h>
class demo
{
int a,b;
public :
demo( )
{
a=b=0;
cout<<“Zero argument constructor called\n”;
show( );
}
demo(int x, int y)
{
a=x;
b=y;
cout<<“Two argument constructor called\n”;
show( );
}
demo(int x)
{
a=b=x;
cout<<“One argument constructor called\n”;
show( );
}
void show( )
{
cout<<“a=”<<a<<“\tb=”<<b<<endl;
}
};
void main( )
{
clrscr( );
demo d1;
demo d2(10,20);
demo d3(30);
getch( );
}

OUTPUT :

Zero argument constructors called


a=0 b=0
Two argument constructor called
a=10 b=20
One argument constructor called
a=30 b=30

4.4 DESTRUCTOR
______________________________________________________________________________________________
A destructor is a member function of the class whose name is same as the name of the class
but the preceded with tilde sign (~). The purpose of destructor is to destroy the object when
it is no longer needed or goes out of scope. As a very small example of destructor see the
program given below :

#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
void main( )
{
clrscr( );
demo d;
getch( );
}
OUTPUT :

Constructor called
Destructor called

4.5 Features of Destructor


______________________________________________________________________________________________
1. The name is same as of class but proceeded with a ~ sign.
2. Destructor is automatically called as soon as an object goes out of scope.
3. Destructor is used to destroy the objects.
4. Once a destructor is called for a object, the object will no longer be available for the future
reference.
5. Destructor can be used for housekeeping work such as closing the file, de-allocating the
dynamically allocated memory etc. Closing a file in destructor is a good idea as user might forget
to close the file associated with object. But as the object goes out of scope destructor will be
called and all code written in destructor executes which will always result in closing the file and
no data loss may be there. When new is used for allocation of memory in the constructor we must
always use delete in the destructor to be allocate the memory.
6. Similar to constructor there is no return type for destructor and that‟s why they cannot return any
value.
7. There is no explicit or implicit category for a destructor. They are always called
implicitly by the compiler.
8. Destructor can never take any arguments.
9. Destructor can be virtual.

Q1. Write a program in C++ to demonstrate the use of destructor.


Q2. Explain the role of destructor in C++ in memory management.
Q3. Define parameterized constructor by taking a C++ program.
Q4. What do you mean by destructor? Explain with example.
Q5. Explain the application of constructors and destructors in C++ programming.
Q6. What do you mean by default constructor? Explain with example.
Q7. What do you mean by constructor in C++ programming?
UNIT – III

CHAPTER – 05

Polymorphism
Chapter Structure :.

5.0 Polymorphism

5.1 Types of Polymorphism

5.2 FUNCTION OVERLOADING

5.3 OPERATOR OVERLOADING

5.4 Binary Operators Overloading in C++

5.5 Unary Operators Overloading in C++

5.6 Comparison / Relational Operators Overloading in C++

5.7 Assignment Operators Overloading in C++

5.8 Conversion Types in C++

5.0 Polymorphism
__________________________________________________________________________________________
Polymorphism is the ability to use an operator or method in different ways. Polymorphism gives
different meanings or functions to the operators or methods. Poly refers many that signify the
many uses of these operators and methods. A single method usage or an operator functioning in
many ways can be called polymorphism. Polymorphism refers to codes, operations or objects
that behave differently in different contexts. “Polymorphism is a mechanism that allows you to
implement a function in different ways.”

Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed
in the same manner even though specific actions associated with each operation may differ.

Example of the concept of polymorphism:

 5+ 20 //The above refers to integer addition.

 The same + operator can be used with different meanings with strings:

 "Tech" + "nical"

 The same + operator can be also used for floating point addition: 2.15 + 10.20
We saw above that a single operator „+‟ behaves differently in different contexts such as integer,
string or float referring the concept of polymorphism. The above concept leads to operator
overloading. When the exiting operator or function operates on new data type it is overloaded.
C++ also permits the use of different functions with the same name. Such functions have
different argument list. The difference can be in terms of number or type of arguments or both. It
refers as function overloading. So, we conclude that the concept of operator overloading and
function overloading is a branch of polymorphism. Both the concepts have been discussed in unit
2 in detail.

5.1 Types of Polymorphism


__________________________________________________________________________________________
C++ provides three different types of polymorphism:

 Function overloading
 Operator overloading
 Virtual functions

Function
Overloading
Compiletime
Polymorphism
Operator
Polymorphism Overloading
in C++
Runtime Virtual
Polymorphism Function

5.2 FUNCTION OVERLOADING


__________________________________________________________________________________________
Function overloading refers to using the same thing for different purposes. C++ permits the use
of different functions with the same name. However such functions essentially have different
argument list. The difference can be in terms of number or type of arguments or both. These
functions can perform a variety of different tasks. This process of using two or more functions
with the same name but differing in the signature is called function overloading. It is only
through these differences that the compiler knows which function to call in any given situations.

Consider the following function:

int add (int a, int b)


{
return a + b;
}

This trivial function adds two integers. However, what if we also need to add two floating point
numbers? This function is not at all suitable, as any floating point parameters would be converted
to integers, causing the floating point arguments to lose their fractional values.

One way to work around this issue is to define multiple functions with slightly different names:

int add (int a, int b)


{
return a + b;
}
Double addition (double p, double q)
{
return p + q;
}

How Function Overloading is Achieved


1) overloading functions that differ in terms of number of parameters

#include<iostream.h>
// function prototype
int func(int i);
int func(int i, int j);
void main(void)
{
cout<<func(15); //func(int i)is called
cout<<func(15,15); //func(int i, int j) is called
}
int func(int i)
{
return i;
}
int func(int i, int j)
{
return i+j;
}

2) overloading functions that differ in terms of types of parameters

#include<iostream.h>
//function prototypes
int func(int i);
double func(double i);
void main(void)
{
cout<<func(15); //func(int i) is called
cout<<func(15.155); //func(double i) is called
}
int func(int i)
{
return i;
}
double func(double i)
{
return i;
}

5.3 OPERATOR OVERLOADING


__________________________________________________________________________________________
We already know that a function can be overloaded (same function name having multiple
bodies). The concept of overloading a function can be applied to operators as well. For example,
in C++ we can multiply two variables of user-defined data type with the same syntax that is
applied to the basic data type. This means that C++ has the ability to provide the operators with a
special meaning for data type. The mechanism which provides this special meaning to operators
is called operator overloading. The operator overloading feature of C++ is one of the methods of
realizing polymorphism. Here, poly refers to many or multiple and morphism refers to actions,
i.e. performing many actions with a single operator. Thus operator overloading enables us to
make the standard operators, like +, -, * etc, to work with the objects of our own data types. So
what we do is, write a function which redefines a particular operator so that it performs a specific
operation when it is used with the object of a class. Operator overloading is very exciting feature
of C++. The concept of operator overloading can also be applied to data conversion. It enhances
the power of extensibility of C++. Thus operator overloading concepts are applied to the
following two principle areas:

 Extending capability of operators to operate on user defined data, and

 Data conversion

General rules for Operator Overloading

 Only built-in operators can be overloaded. If some operators are not present in C++, we
cannot overload them.
 The arity of the operators cannot be changed
 The precedence of the operators remains same.
 The overloaded operator cannot hold the default parameters except function call operator
“()”.
 We cannot overload operators for built-in data types. At least one user defined data types
must be there.
 The assignment “=”, subscript “[]”, function call “()” and arrow operator “->” these
operators must be defined as member functions, not the friend functions.
 Some operators like assignment “=”, address “&” and comma “,” are by default
overloaded.

5.4 Binary Operators Overloading in C++


__________________________________________________________________________________________
When overloading binary operator using operator function as class member function, the left
side operand must be an object of the class and right side operand may be either a built-in type
or user defined type. The other method using friend function will be discussed later on. We
present numerous program of overloading binary operators.
The binary operators take two arguments and following are the examples of Binary operators.
You use binary operators very frequently like addition (+) operator, subtraction (-) operator and
division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar way, you can
overload subtraction (-) and division (/) operators.
#include <iostream>
using namespace std;

class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

public:

double getVolume(void) {
return length * breadth * height;
}

void setLength( double len ) {


length = len;
}

void setBreadth( double bre ) {


breadth = bre;
}

void setHeight( double hei ) {


height = hei;
}

// Overload + operator to add two Box objects.


Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;

return 0;
}
Output :-
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

5.5 Unary Operators Overloading in C++


__________________________________________________________________________________________
Similar to overloading binary operator we can overload unary −, pre and post ++, pre and post
– and unary +. In case of overloading binary operators using member function of class left
operand is responsible for calling the operator function and right operand was send as argument.
In case of unary operator only one operand is there and this operand itself calls the overloaded
operator function. Nothing is send as argument to the function. Its general syntax is (defined with
the class)
The unary operators operate on a single operand and following are the examples of Unary
operators −

 The increment (++) and decrement (--) operators.


 The unary minus (-) operator.
 The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this
operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can
be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as
postfix usage.

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

Output :-
F: -11 I:-10
F: 5 I:-11

5.6 Comparison / Relational Operators Overloading in C++


__________________________________________________________________________________________
There are various relational operators supported by C++ language like (<, >, <=, >=, ==, etc.)
which can be used to compare C++ built-in data types.
You can overload any of these operators, which can be used to compare the objects of a class.
Following example explains how a < operator can be overloaded and similar way you can
overload other relational operators.

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}

// overloaded < operator


bool operator <(const Distance& d) {
if(feet < d.feet) {
return true;
}
if(feet == d.feet && inches < d.inches) {
return true;
}

return false;
}
};

int main() {
Distance D1(11, 10), D2(5, 11);

if( D1 < D2 ) {
cout << "D1 is less than D2 " << endl;
} else {
cout << "D2 is less than D1 " << endl;
}

return 0;
}
Output :-
D2 is less than D1

5.7 Assignment Operators Overloading in C++


You can overload the assignment operator (=) just as you can other operators and it can be used
to create an object just like the copy constructor.
Following example explains how an assignment operator can be overloaded.

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
void operator = (const Distance &D ) {
feet = D.feet;
inches = D.inches;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};

int main() {
Distance D1(11, 10), D2(5, 11);

cout << "First Distance : ";


D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();

// use assignment operator


D1 = D2;
cout << "First Distance :";
D1.displayDistance();

return 0;
}
Output :-
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11

5.8 Conversion Types in C++


__________________________________________________________________________________________
Many times in programming situations we like to convert one data type into another. Converting
data types of a variable into other data type is known as type conversion. We have studied it
earlier when we convert int to float, char to int, double to int etc. Compiler also does implicit
type conversion. But all we studied involved all built-in types. In this section, we study type
conversion with respect to user data type viz. class. We divide the study of type conversion into
three parts.
1. Conversion from Built-in types to class type.
2. Conversion from class type to built-in types.
3. Conversion from one class type to another.

1) Conversion from built in type to class type :

A constructor is used to build a matrix object from an int type array. Similarly, we used another
constructor to build a string type object from char* type variable. In below examples
constructors performed a defacto type conversion from the argument's type to the constructor's
class type.

Consider the following constructor :-

string :: string(char*a)
{
length = strlen(a);
name = new char [len + 1];
strcpy(name,a);
}

This constructor builds a string type object from char* type variable a. The variables length and
name are data members of the class string. Once we define the constructor in the class string, it
can be used for conversion from char* type to string type.
Example 1:

string s1 , s2;
char* name1 = " Good Morning " ;
char* name2 = " Students " ;
s1 = string ( name1 ) ;
s2 = name2 ;
Explanation :-

s1 = string ( name1 ) ;
In the above code snippet, first converts name1 from char* type to string type and then assigns
the string type values to the object s1.

The statement below performs the same job by invoking the constructor implicitly.:

s2 = name2 ;

Example 2:

class time
{
int hours;
int minutes;
public :
void time ( int t ) // II constructor
{
hours = t / 60 ; // t is inputted in minutes
minutes = t % 60 ;
}
};

Explanation :-

time t1; // object t1 created


int period = 160;
t1 = period; // int to class type
The object t1 is created. The variable period of data type integer is converted into class type time
by invoking the constructor. After the conversion, the data member hours of T1 will have value 2
and minutes will have a value of 40 denoting 2 hours and 40 minutes.
Note that constructors are used for the type conversion take a single argument whose type is to
be converted.

Note : In both the examples, the left-hand operand of = operator is always a class object. Hence,
we can also accomplish this conversion using an overloaded = operator.

2) Conversion from class type to built in 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 :

operator typename()
{
// Program statement
}
Example :

In the below example, operator double () converts a class object to type double.

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 :-

It must be a class member.


It must not specify a return type.
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.

3) 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.

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.

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 ;
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 ;
}

Q1. What are the basic rules for operator overloading in C++?
Q2. What is dynamic binding?
Q3. Describe the concept of polymorphism
Q4. What is function overloading?
Q5. What are the main applications of function overloading?
Q6. Explain the concept of operator overloading?
Q7. What are the limitations of Operator overloading and Functional overloading?
UNIT – III

CHAPTER – 06

Virtual Functions
Chapter Structure :

6.0 Virtual Functions

6.1 Rules of Virtual Function

6.2 Limitations of Virtual Functions

6.3 Need of Virtual Function

6.4 Pure Virtual Function

6.5 Static Functions and Member Functions

6.6 this Pointer

6.7 Abstract Classes

6.8 Virtual Destructor in C++

6.0 Virtual Functions


__________________________________________________________________________________________
o A C++ virtual function is a member function in the base class that you redefine in a
derived class. It is declared using the virtual keyword.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, always
executes the base class function. This issue can only be resolved by using the 'virtual'
function.

6.1 Rules of Virtual Function


__________________________________________________________________________________________
o Virtual functions must be members of some class.
o Virtual functions cannot be static members.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will
consider them as the overloaded functions

6.2 Limitations of Virtual Functions


__________________________________________________________________________________________
 The function call takes slightly longer due to the virtual mechanism, and it also makes it
more difficult for the compiler to optimize because it doesn't know exactly which
function is going to be called at compile time.
 In a complex system, virtual functions can make it a little more difficult to figure out
where a function is being called from.
 Virtual functions will usually not be inlined.
 Size of object increases due to virtual pointer.

1. #include <iostream.h>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }
Output:

Derived Class is invoked

6.3 Need of Virtual Function


____________________________________________________________________________________

The first and foremost question which is arises why do we need virtual function? Suppose we do
have a list of pointer to objects of a super class in an inheritance hierarchy and we wish to invoke
the functions of its derived classes with the help of single list of pointers provided that the
functions in super class and sub classes have the same name and signature. That in turn means
we want to achieve run time polymorphism.

6.4 Pure Virtual Function


__________________________________________________________________________________________
o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual function
is a function declared in the base class that has no definition relative to the base class.
o A class containing the pure virtual function cannot be used to declare the objects of its
own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes and to
create the base pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:

virtual void display() = 0;

Example :-
1. #include <iostream.h>
2. class Base
3. {
4. public:
5. virtual void show() = 0;
6. };
7. class Derived : public Base
8. {
9. public:
10. void show()
11. {
12. std::cout << "Derived class is derived from the base class." << std::endl;
13. }
14. };
15. int main()
16. {
17. Base *bptr;
18. //Base b;
19. Derived d;
20. bptr = &d;
21. bptr->show();
22. return 0;
23. }

Output:

Derived class is derived from the base class.

6.5 Static Functions and Member Functions

_____________________________________________________________________________________

Static functions and members can be simply defined as the functions and members which can be
accessed through the class name. We do not need to create the instance/object of the class in
order to access the static members of the class. Static members are per class where as non-static
members are per instance. An interesting thing is that value of the static members of the class is
same for all objects and if static member is publicly defined, any object of the class can modify
the value of static members and this value will be updated for all the instances.

#include <iostream.h>
#include <fstream.h>
#include <string.h>

class ObjectCounter
{

public:
static int numofobjects;
public:
ObjectCounter()
{
numofobjects ++;
}
static void showcount()
{
cout<<"Total number of Objects is: "<<numofobjects<<endl;
}
};

int ObjectCounter ::numofobjects = 0;

int main()
{
ObjectCounter::showcount();
ObjectCounter a, b, c;
cout<<"After instantiating ObjectCounter Class thrice."<<endl;
ObjectCounter::showcount();
}

6.6 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.
Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.
Let us try the following example to understand the concept of this pointer −

#include <iostream>

using namespace std;

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(5.6, 1.2, 5.1); // Declare box1
Box Box2(2.5, 4.1, 6.1); // Declare box2

if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}

return 0;
}
Output :
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

6.7 Abstract Classes


__________________________________________________________________________________________
Abstract classes act as a container of general concepts from which more specific classes can be
inherited. Thus an abstract class is one that is not used to create any object of its own but it solely
exists to act as a base class for the other classes that means the abstract class must be a part of
some inheritance hierarchy.

An abstract class can further be illuminated through following points:

 An abstract class can not be instantiated that means abstract classes can not have their
own instances but their child or derived classes may have their own instances provided
the child class itself is not an abstract class.

 Though objects of an abstract class cannot be created, however, one can use pointers and
references to abstract class types.

 A class should contain at least one pure virtual function to be called as abstract. Pure
virtual functions can be declared with the keyword virtual and =0 syntax at the end of
function declaration statement.
 If a class is made abstract by giving a pure virtual function then it must be inherited by a
child class of it that provides the implementation of the pure virtual function.

 If a class inherits an abstract class and does not provide the implementation of the pure
virtual function then the child class itself should declare the function as pure virtual that
means the child class will be an abstract class as well.

 The signature of the function declared as pure virtual in base class must strictly agree
with the signature of the function in child class that implements the pure virtual function.

//Abstract base class


class Base
{
public:
virtual void show() = 0; // Pure Virtual Function
};

class Derived : public Base


{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class\n";
}
};

int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}

Output :-

Implementation of Virtual Function in Derived class

6.8 Virtual Destructor in C++


__________________________________________________________________________________________

A destructor in C++ is a member function of a class used to free the space occupied by or delete
an object of the class that goes out of scope. A destructor has the same name as the name of the
constructor function in a class, but the destructor uses a tilde (~) sign before its function name.
Virtual Destructor

A virtual destructor is used to free up the memory space allocated by the derived class object or
instance while deleting instances of the derived class using a base class pointer object. A base or
parent class destructor use the virtual keyword that ensures both base class and the derived class
destructor will be called at run time, but it called the derived class first and then base class to
release the space occupied by both destructors.

Why we use virtual destructor in C++?

When an object in the class goes out of scope or the execution of the main() function is about to
end, a destructor is automatically called into the program to free up the space occupied by the
class' destructor function. When a pointer object of the base class is deleted that points to the
derived class, only the parent class destructor is called due to the early bind by the compiler. In
this way, it skips calling the derived class' destructor, which leads to memory leaks issue in the
program. And when we use virtual keyword preceded by the destructor tilde (~) sign inside the
base class, it guarantees that first the derived class' destructor is called. Then the base class'
destructor is called to release the space occupied by both destructors in the inheritance class.

1. #include<iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. Base() // Constructor member function.
7. {
8. cout << "\n Constructor Base class"; // It prints first.
9. }
10. virtual ~Base() // Define the virtual destructor function to call the Destructor Derived function.
11. {
12. cout << "\n Destructor Base class"; /
13. }
14. };
15. // Inheritance concept
16. class Derived: public Base
17. {
18. public:
19. Derived() // Constructor function.
20. {
21. cout << "\n Constructor Derived class" ; /* After print the Constructor Base, now it will prints.
*/
22. }
23. ~Derived() // Destructor function
24. {
25. cout << "\n Destructor Derived class"; /* The virtual Base Class? Destructor calls it before call
ing the Base Class Destructor. */
26. }
27. };
28. int main()
29. {
30. Base *bptr = new Derived; // A pointer object reference the Base class.
31. delete bptr; // Delete the pointer object.
32. }

Output:

Q1. What are the Rules of Virtual Function ?


Q2. What is virtual function ? Explain with example .
Q3. What are the Limitations of Virtual Functions ?
Q4. What is pure virtual function ? Explain
Q5. Write a note on " this Poinrer" & " Abstract class "
Q6. What is virtual Distructor ? Explain with example .

You might also like