You are on page 1of 75

UNIT I

Introduction to OOP :
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods).

Object-oriented programming aims to implement real-world entities like inheritance, hiding,


polymorphism etc in programming.

The main aim of OOP is to bind together the data and the functions that operate on them so that
no other part of the code can access this data except that function.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc. 

Building blocks of object-oriented programming include the following:

 Classes are user-defined data types that act as the blueprint for individual objects, attributes
and methods.

 Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity.

 Methods are functions that are defined inside a class that describe the behaviors of an object.

 Attributes are defined in the class template and represent the state of an object. Objects will
have data stored in the attributes field.

Benefits of OOP ( 7 marks)


 We can build the programs from standard working modules that communicate with one
another to save development time and higher productivity,
 OOP language allows to break the program into the bit-sized problems that can be solved
easily (one object at a time).
 It improves programmer productivity, better quality of software and lesser maintenance
cost.
 OOP systems can be easily upgraded from small to large systems.
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 It provides effective problem solving oop approach to divide a problem in to objects.
 The principle of data hiding helps the programmer to build secure programs ,

1
 By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
 Message passing techniques is used for communication between objects .
Application of OOPs in C++ (10 marks)

 Real-Time System design: Real-time system inherits complexities and makes it difficult to


build them. OOP techniques make it easier to handle those complexities.
 Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored,
searched, and edited easily. Hypermedia on the other hand is a superset of hypertext. OOP
also helps in laying the framework for hypertext and hypermedia.
 AI Expert System: These are computer application that is developed to solve complex
problems which are far beyond the human brain. OOP helps to develop such an AI expert
System
 Office automation System: These include formal as well as informal electronic systems
that primarily concerned with information sharing and communication to and from people
inside and outside the organization. OOP also help in making office automation principle.
 Neural networking and parallel programming: It addresses the problem of prediction
and approximation of complex-time varying systems. OOP simplifies the entire process by
simplifying the approximation and prediction ability of the network.
 Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and
understanding interaction explicitly. OOP provides an appropriate approach for simplifying
these complex models.
 Object-oriented database: The databases try to maintain a direct correspondence between
the real world and database object in order to let the object retain it identity and integrity.
 Client-server system: Object-oriented client-server system provides the IT infrastructure
creating object-oriented sever internet(OCSI) applications.
 CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing
applications as it allows people to reduce the efforts involved. For instance, it can be used
while designing blueprints and flowcharts. So it makes it possible to produce these
flowcharts and blueprint accurately.

Basic concepts of object oriented programming (10 marks)


Key concepts of OOP are

 class
 objects
 encapsulation
 polymorphism
 inheritance
 abstraction
2
Class − A class is a data-type that has its own members i.e. data members and member functions.
It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in c++.
The members of a class are accessed in programming language by creating an instance of the
class.
Some important properties of class are −
 Class is a user-defined data-type.
 A class contains members like data members and member functions.
 Data members are variables of the class.
 Member functions are the methods that are used to manipulate data members.
 Data members define the properties of the class whereas the member functions define the
behaviour of the class.
A class can have multiple objects which have properties and behaviour that in common for all
of them.
Syntax
class class_name
{
   data_type data_name;
   return_type method_name(parameters);
}

Object − An object is an instance of a class. It is an entity with characteristics and behaviour that
are used in the object oriented programming. An object is the entity that is created to allocate
memory. A class when defined does not have memory chunk itself which will be allocated as
soon as objects are created.
Syntax
class_name object_name;

Encapsulation In object oriented programming, encapsulation is the concept of wrapping


together of data member and member functions in a single unit.
A formal definition of encapsulation would be: encapsulation is binding together the data and
related function that can manipulate the data.
Polymorphism : The name defines polymorphism is multiple forms which means
polymorphism is the ability of object oriented programming to do some work using multiple
forms. The behaviour of the method is dependent on the type or the situation in which the
method is called.

3
Operator overloading In operator overloading , operator can have multiple behaviour in
different instances of usage.
Function overloading Functions with the same name that can do multiple types of tasks based
on some condition.
Inheritance it is the capability of a class to inherit or derive properties or characteristics other
class. it is very important and object oriented program as it allows reusability i.e. using a method
defined in another class by using inheritance. The class that derives properties from other class is
known as child class or subclass and the class from which the properties are inherited is base
class or parent clas

Abstraction Data abstraction or Data Hiding is the concept of hiding data and showing only
relevant data to the final user. It is also an important part of object oriented programing.

C++ program structure


C++ program structure is divided into various sections, namely, headers, class
definition, member functions definitions  and main function.

Headers: Generally, a program includes various programming elements like built-in functions,


classes, keywords, constants, operators, etc., that are already defined in the standard C++ library.

Class Definition: classes are defined using keyword “class “

Member function definition : member functions are defined inside class.

Main Function: The main () is a startup function that starts the execution of a c++ program. All
C++ statements that need to be executed are written within main ( ). 


Eg:

4
#include <iostream.h>
using namespace std;

int main() 
{
  cout << "Hello World!" << endl;
  return 0;
}

 #include is a specific preprocessor command.

It copies and pastes the entire text of the file, specified between the angle brackets, into
the source code.

 The file <iostream> input-output streams is a standard file that comes with the C++
compiler.

It contains code for displaying and getting an input from the user.

 namespace is a prefix that is applied to all the names in a certain set.

Namespace permits grouping of various entities like classes, objects, functions and
various C++ tokens, etc., under a single name.

 iostream file defines two names used in this program - cout and endl.

UNIT-II

Tokens :
A token is the smallest element of a program that is meaningful to the compiler.
Different kinds of Tokens are as follows:  
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1.Keywords: Keywords are pre-defined or reserved words in a programming language.


 C language supports 32 keywords which are given below: 
auto double int struct
break else long switch
5
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

While in C++ there are 31 additional keywords other than C Keywords they are: 

asm bool catch class


const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

2.Identifiers: 

 Identifiers are names of variables, functions and arrays.


 Identifiers are user-defined names consisting of letters and digits with either a letter or
the underscore(_) as a first character.
 keywords cannot be used as identifiers
Eg: int number;
Void getdata( );


Rules to be followed to name c++ identifiers: 
 
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.

3.Constants: 
 Constants refer to fixed values.
 They are also called literals. 
 Constant values can not be modified by the program once they are defined.
Constants may belong to any of the data type

 Different Types of Constants: 


 
1. Integer constants – Example: 0, 1, 1218, 12482
6
2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “God is good”

4.Strings: 
 A String is an array of characters ended with a null character (‘\0’).
 Null character indicates the end of the string.
 Strings are always enclosed in double-quotes.
 A character is enclosed in single quotes in C and C++.
 Declarations of String: 
 
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘ k’ , ‘ s’ , ‘ \0’ };
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

5. Special Symbols: 
The following special symbols are used in C++ having some special meaning and thus, cannot
be used for some other purpose.[] () {}, ; * = # 
 Brackets[ ]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and function
parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (, ): It is used to separate more than one statements like for separating parameters
in function calls.
 Colon(:): It is an operator that essentially invokes something called an initialization list.
 Semicolon(;): It is known as a statement terminator.  It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): It is used to create a pointer variable.
 Assignment operator(=): It is used to assign values.
 Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.

6.Operators in C++ :
 Operators are symbols that trigger an action when applied to C++ variables and other
objects.
 The data items on which operators act upon are called operands. 

Operators can be classified as follows: 


 
Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators.
Eg: increment ++and decrement - - operators
7
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into : 
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators

Arithmetic Operators

There are following arithmetic operators supported by C++ language −

Operato Description Example


r

+ Adds two operands A + B will give


30

- Subtracts second operand from the first A - B will give


-10

* Multiplies both operands A * B will give


200

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

% Modulus Operator and remainder of after an B % A will give


integer division 0

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


by one

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


by one

8
Relational Operators

There are following relational operators supported by C++ language

Operator Description Example

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


or not, if yes then condition becomes true.

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


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

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

< Checks if the value of left operand is less than (A < B) is true.
the value of right operand, if yes then condition
becomes true.

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

<= Checks if the value of left operand is less than (A <= B) is true.
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.

Operator Description Example

9
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition becomes
true.

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


operands is non-zero, then condition becomes
true.

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


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
10
A^B = 0011 0001
~A  = 1100 0011

Operator Description Example

& Binary AND Operator copies a bit to the result


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

| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.

^ Binary XOR Operator copies the bit if it is set


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

~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.

<< Binary Left Shift Operator. The left operands


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

>> Binary Right Shift Operator. The left operands


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

Assignment Operators

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

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

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

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

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

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

%= Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to C = C


operands and assign the result to left operand. %A

Miscellaneous 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.

12
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.

C++ Data Types


 All variables use data-type during declaration to restrict the type of data to be stored.

 Compiler allocates some memory for that variable based on the data-type with which it is
declared.

 Every data type requires a different amount of memory.


 

13
Data types in C++ is mainly divided into three types: 
 
1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc. Primitive data
types available in C++ are: 
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

 
 Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647. 
 
 Character: Character data type is used for storing characters. Keyword used for character
data type is char. Characters typically requires 1 byte of memory space and ranges from -128
to 127 or 0 to 255. 
 
 Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable
can store either true or false. Keyword used for boolean data type is bool. 
 
 Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float variables
14
typically requires 4 byte of memory space. 
 
 Double Floating Point: Double Floating Point data type is used for storing double precision
floating point values or decimal values. Keyword used for double floating point data type
is double. Double variables typically requires 8 byte of memory space. 
 
 void: Void means without any value. void datatype represents a valueless entity. Void data
type is used for those function which does not returns a value. 
 
 Wide Character: Wide character data type is also a character data type but this data type has
size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4
bytes long. 

2.Derived Data Types:


 Data types that are derived from the built-in data types are known as derived data types.
 The various derived data types provided by C++ are 
1.arrays
2.functions
3. references 
4. pointers.
Array  An array is a set of elements of the same data type that are referred to by the same name.
All the elements in an array are stored at contiguous (one after another) memory locations and
each element is accessed by a unique index or subscript value. The subscript value indicates the
position of an element in an array.
Function  A function is a self-contained program segment that carries out a specific well-defined
task. In C++, every program contains one or more functions which can be invoked from other
parts of a program, if required.
Reference  A reference is an alternative name for a variable. That is, a reference is an alias for a
variable in a program. A variable and its reference can be used interchangeably in a program as
both refer to the same memory location. Hence, changes made to any of them (say, a variable)
are reflected in the other (on a reference).
Pointer A pointer is a variable that can store the memory address of another variable. Pointers
allow to use the memory dynamically. That is, with the help of pointers, memory can be
allocated or de-allocated to the variables at run-time, thus, making a program more efficient.

3.User-DefinedDataTypes
Various user-defined data types provided by C++ are  structures, unions,
enumerations and classes.

15
STRUCTURE
Structure is a collection of variables (can be of different data types) under a single name.

How to define a structure?

Keyword struct is used for creating a structure.


Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member n;
};
Here is an example:
struct employee
{
char name[20];
int no;
float salary;
};

structure variable

When a structure is defined, it creates a user-defined type. However, no storage or memory is


allocated. To allocate memory of a given structure type and work with it, we need to create
variables. 
Here's how we create structure variables:

struct person
{
char name[50];
int no;
float salary;
};

int x,y,z;
int main()
{
struct person person1, person2, p[20];
return 0;
}

16
UNION
● Union allocates one common storage space for all its members
● We can access only one member of union at a time
● Many union variables can be created in a program and memory will be allocated for each
union variable separately.
EXAMPLE:
#include <stdio.h>
#include <string.h>
 union student
{
            char name[20];
            char subject[20];
            float percentage;
};
 int main()
{
    union student record1;
    union student record2;
        strcpy(record1.name, "Raju");
       strcpy(record1.subject, "Maths");
       record1.percentage = 86.50;
        printf("Union record1 values example\n");
       printf(" Name       : %s \n", record1.name);
       printf(" Subject    : %s \n", record1.subject);
       printf(" Percentage : %f \n\n", record1.percentage);
       printf("Union record2 values example\n");
       strcpy(record2.name, "Mani");
       printf(" Name       : %s \n", record2.name);
        strcpy(record2.subject, "Physics");
       printf(" Subject    : %s \n", record2.subject);
        record2.percentage = 99.50;
       printf(" Percentage : %f \n", record2.percentage);
       return 0;
}
Class − A class is a data-type that has its own members i.e. data members and member functions.
It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in c++.
The members of a class are accessed in programming language by creating an instance of the
class.
Some important properties of class are −
 Class is a user-defined data-type.
 A class contains members like data members and member functions.
17
 Data members are variables of the class.
 Member functions are the methods that are used to manipulate data members.
 Data members define the properties of the class whereas the member functions define the
behaviour of the class.
A class can have multiple objects which have properties and behaviour that in common for all of
them.
Syntax
class class_name {
   data_type data_name;
   return_type method_name(parameters);
}

C++ offers a new user-defined data type known as class, which forms the basis of object-
oriented programming.
A class acts as a template which defines the data and functions that are included in an object of
a class.
Classes are declared using the keyword class. Once a class has been declared, its object can be
easily created.
Enumeration: An enumeration is a set of named integer constants that specify all the
permissible values that can be assigned to enumeration variables.
These set of permissible values are known as enumerators.
Eg:
enum country {US, UN, India, China};       // declaring an
                                                                                     //  enum type
typedef 
 
 C++ provides a typedef feature that allows to define new data type names for existing
data types that may be built-in, derived or user-defined data types.
 Once the new name has been defined, variables can be declared using this new name.

Eg :
                                               typedef int integer;

18
In this declaration, a new name integer is given to the data type into This new name now can be
used to declare integer variables as shown here.
                                                 integer i, j, k;

Declaration of variables in C++

A typical variable declaration is of the form: 


 
// Declaring a single variable
datatype variable_name;

// Declaring multiple variables:


datatype variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.

A storage class defines the scope (visibility) and life-time of variables and/or functions within a
C++ Program.
These specifiers precede the type that they modify.
There are following storage classes, which can be used in a C++ Program

 auto
 register

19
 static
 extern
 mutable

auto Storage Class

The auto storage class is the default storage class for all local variables.

int mount;
auto int month;

Auto can only be used within functions, i.e., local variables.

register Storage Class

The register storage class is used to define local variables that should be stored in a register
instead of RAM.
This means that the variable has a maximum size equal to the register size (and can't have the
unary '&' operator applied to it .

register int miles;

The register should only be used for variables that require quick access such as counters.
It should also be noted that defining 'register' does not mean that the variable will be stored in a
register.
static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program.
In C++, when static is used on a class data member, it causes only one copy of that member to
be shared by all objects of its class.
#include <iostream.h>

// Function declaration
void func(void);

static int count = 10; /* Global variable */

main() {
while(count--) {
func();
20
}

return 0;
}

// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
cout << "i is " << i ;
cout << " and count is " << count;
cout<<endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to all the
program files.
When you use 'extern' the variable cannot be initialized as all it does is point the variable name
at a storage location that has been previously defined.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
#include <iostream>

extern int count;

void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}

mutable Storage Class

The mutable specifier applies only to class objects.


21
It allows a member of an object to override const member function.

C++ Manipulators

 Manipulators are operators used in C++ for formatting output. The data is manipulated
by the programmer’s choice of display.

endl Manipulator:
 This manipulator has the same functionality as the ‘n’ newline character.

For example:
1. cout << "Exforsys" << endl; 
2. cout << "Training";

 Exforsys

Training

setw Manipulator:
 This manipulator sets the minimum field width on output.

Syntax:

setw(x)
 Here setw causes the number or string that follows it to be printed within a field of x
characters wide and x is the argument set in setw manipulator.
 The header file that must be included while using setw manipulator is .

Example:

#include <iostream>
#include <iomanip> 
 
void main( )
{
int x1=123,x2= 234, x3=789;
cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl

22
<< setw(8) << "test123" << setw(20)<< x1 << endl
<< setw(8) << "exam234" << setw(20)<< x2 << endl
<< setw(8) << "result789" << setw(20)<< x3 << endl;
}

Output:
test                  123
exam                  234
result                  789

setfill Manipulator:
 This is used after setw manipulator.
 If a value does not entirely fill a field, then the character specified in the setfill argument
of the manipulator is used for filling the fields.

Example:

#include <iostream>
#include <iomanip>
void main()
{
cout << setw(15) << setfill('%') << 99 << 97 << endl;
}

Output
%%%%%%%%%%%9997
 

setprecision Manipulator:
 The setprecision Manipulator is used with floating point numbers.
 It is used to set the number of digits printed to the right of the decimal point.
 This may be used in two forms:

1. fixed

23
2. scientific

 These two forms are used when the keywords fixed or scientific are appropriately used
before the setprecision manipulator.
 The keyword fixed before the setprecision manipulator prints the floating point number in
fixed notation.
 The keyword scientific, before the setprecision manipulator, prints the floating point
number in scientific notation.

Example:

#include <iostream>
#include <iomanip>
void main( )
{
float x = 0.1;
cout << fixed << setprecision(3) << x << endl;
cout << scientific << x << endl;
}

Output:
0.100
1.000e-001

 
 The first cout statement contains fixed notation and the setprecision contains argument 3.
 This means that three digits after the decimal point and in fixed notation will output the
first cout statement as 0.100. The second cout produces the output in scientific notation.
 The default value is used since no setprecision value is provided.

EXPRESSION IN C++

24
Expression: An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to produce a
value.

Types of Expressions:
Expressions may be of the following types:
 Constant expressions: Constant Expressions consists of only constant values. A constant
value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
 Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
 Floating expressions: Float Expressions are which produce floating point results after
implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool which takes a
value true or false. When arithmetic expressions are used on either side of a relational
operator, they will be evaluated first and then the results compared. Relational expressions
are also known as Boolean expressions.
Examples:
x <= y, x + y > 2

25
 Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
 Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
 Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.

Control structures
In C++, control flow statements are used to alter, redirect, or to control the flow of program
execution based on the application logic.

Types of Control Flow Statement


In C++, Control flow statements are mainly categorized in following types –

 Selection statements
 Iteration statements

26
 Jump statements

C++ Selection Statements


In C++, Selection statements allow you to control the flow of the program during run time on the
basis of the outcome of an expression or state of a variable. Selection statements are also referred
to as Decision making statements. Selection statements evaluates single or multiple test
expressions which results in “TRUE” or “FALSE”. The outcome of the test
expression/condition helps to determine which block of statement(s) to executed if the condition
is “TRUE” or “FALSE” otherwise.
In C++, we have following selection statements –
 C++ If-else Statements

In C++, when we want to execute a block of code when if condition is true and another block of
code when if condition is false, In such a case we use if…else statement.

27
Syntax
1 if(condition){

2 // statements

3 } else {

4 // statements

5}
Here, Condition is a Boolean expression that results in either True or False, if it results
in True then statements inside if body are executed, if it results in False then statements inside
else body are executed.

#include <iostream.h>

using namespace std;

int main()

  int a = 10;

  int b = 20;

28
  cout<<" Finding bigger ";

  if(a > b)

  cout<<"\n a is greater than b";

  }

  else

  cout<<"\n b is greater than a";

  }

     return 0;

  

}
Output:-

Finding Bigger

B is greater than a

C++ Switch Statements

A switch case statement evaluates an expression against multiple cases in order to


identify the block of code to be executed.

29
Syntax:-
switch(expression)
{
case value1:
// statements
        break;
case value2:
// statements
        break;
default:
// statements
        break;
}

30
C++ Iteration Statements
In C++, Iteration statements are used to execute the block of code repeatedly for a specified
number of times or until it meets a specified condition. Iteration statements are commonly
known as loops or looping statements.
In C++, we have following iteration statements available-

for Loop
The for loop is used when we want to execute block of code known times. In C++, basic for loop
is similar as it is in C. The for loop takes a variable as iterator and assign it with an initial value,
and iterate through the loop body as long as the test condition is true. Once the loop statements
are executed for current iteration, the iterator is updated with new value and if the test condition
is still valid, we loop another time. When test condition return a false value, the for loop is
ended.
Syntax
for(Initialization; Condition; incr/decr)
{
// loop body
}

The for loop has three components separated by semicolons.


initialization :- In this section is used to declare and initialize the loop iterator. This is the first
statement to be executed and executed only once at the beginning.
condition :- Next, the test condition is evaluated before every iteration, and if it returns a true
value then the loop body is executed for current iteration. If it returns a false value then loop is
terminated and control jumps to the next statement just after the for loop.
incr/decr :- Once, the loop body is executed for current iteration then the incr/decr statement is
executed to update the iterator value and if the test condition is evaluated again. If it returns a
true value then the loop body is executed another time. If test condition returns a false value then
loop is terminated and control jumps to the next statement just after the for loop.

31
#include <iostream>
 
using namespace std;
 
int main()
{
    cout<<” C++ for loop";
    for(int ctr=1;ctr<=5;ctr++){      
        cout<<"\n"<<ctr;      
    }
 
    return 0;
}

While Loop
The while loop will execute a block of statement as long as a test expression is true.
While loop is useful when the number of iterations can not be predicted beforehand. The while
loop evaluates test expression at beginning of each pass.

32
Syntax
while(condition)
{
    // loop body
}

Eg:
#include <iostream>
 
using namespace std;
 
int main()
{
    int ctr =1;
    int maxCtr =5;
    cout<<" C++ while loop";
    while(ctr<=maxCtr){      
        cout<<"\n"<<ctr;  
        ctr = ctr+1;
    }
 
    return 0;
33
}

do while Loop
The do…while loop executes block of statements inside loop body first and then test the
condition for next iteration and executes next only if condition is true. The do…while loop is
much similar to C++ while loop with one major difference, in do…while loop block of statements
inside loop body executes at least once.

Syntax
do{
    // loop body
} while(condition);
Here, loop executes block of statements inside loop body first and then test
the condition provided along with while keyword for next iteration and executes next only
if condition is true. Condition is a Boolean expression that results in either True or False, if it
results in True then statements inside loop body are executed and condition is evaluated again.
This process is repeated until the condition is evaluated to False. If the condition results
in False then loop is terminated and control is transferred to next statement.

#include <iostream>
 
using namespace std;

34
 
int main()
{
    int ctr =1;
    int maxCtr =5;
    cout<<"W3Adda - C++ do while loop";
    do{      
        cout<<"\n Hello World! Value IS : "<<ctr;  
        ctr = ctr+1;
    }while(ctr<=maxCtr);
 
    return 0;
}

Continue Statement
In C++, the continue statement gives you way to skip over the current iteration of any loop.
When a continue statement is encountered in the loop, the rest of statements in the loop body for
current iteration and returns the program execution to the very first statement in the loop body. It
does not terminates the loop rather continues with the next iteration.

#include <iostream>
 
using namespace std;
 
int main()
{
35
    int ctr = 0;
    
    cout<<" C++ Continue Statement";
    while(ctr < 10)
{
        ctr = ctr + 1;
        if(ctr = = 5)
{
            cout<<"\n5 is skipped";
            continue;
        }
        cout<<"\nNumber is "<<ctr;
    }
    cout<<"\nOut of while loop";
 
    return 0;
}

goto statement
In C++, goto statement is used to alter the normal execution of a program and transfer control to
a labeled statement in the same program. In a C++ program we can have multiple goto and label
statements, the goto statement is followed by a label name. Label is an identifier, which can be
any plain text and can be set anywhere in a C++ program above or below to goto statement.
When a goto statement is encountered, compiler transfers the control to a label: specified with
goto statement and begin execution from there.

Syntax:
goto label;

#include <iostream>
 
using namespace std;
 
int main()
{
    int age;
    cout<<" C++ goto Statement";
    election:
    cout<<"\nEnter your age :";
    cin>>age;

    if (age <= 17)


36
{
      cout<<"\nYou are not eligible to vote.";  
      goto election;  
     }
else
{  
      cout<<"You are eligible to vote.";
     }  
    return 0;
}

Break Statement
In C++, break statement inside any loop gives you way to break or terminate the execution of
loop containing it, and transfers the execution to the next statement following the loop. It is
almost always used with if..else construct.

#include <iostream>
 
using namespace std;
 
int main()
{
37
    int count = 0;
    
    cout<<" C++ Break Statement";
    while(count <= 10){
        count = count + 1;
        if(count == 5){
            break;
        }
        cout<<"\nInside loop "<<count;
    }
    cout<<"\nOut of while loop";
 
    return 0;
}

UNIT -3
C++ Functions
A function is a group of statements that together perform a task. Every C++ program has at least
one function, which is main(), and all the most trivial programs can define additional functions.

A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function

The general form of a C++ function definition is as follows −


return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The

38
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.

Example

int max (int num1, int num2)


{
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations

A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file
calling the function.

Calling a Function

To use a function, we have to call or invoke that function.


When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when it’s return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
39
o
#include <iostream>
using namespace std;

// function declaration
int max(int num1, int num2);

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Output :

Max value is : 200

40
C++ function call by reference
The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. The changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other
value.
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */

return;
}

Eg: Passing values by reference


#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
41
After swap, value of b :100

Returning values by reference in C++

When a function returns a reference, it returns an implicit pointer to its return value. This way, a
function can be used on the left side of an assignment statement.

include <iostream>
#include <ctime>

using namespace std;

double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};

double& setValues( int i ) {


return vals[i]; // return a reference to the ith element
}

// main function to call above defined function.


int main () {

cout << "Value before change" << endl;


for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}

setValues(1) = 20.23; // change 2nd element


setValues(3) = 70.8; // change 4th element

cout << "Value after change" << endl;


for ( int i = 0; i < 5; i++ ) {
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}

When the above code is compiled together and executed, it produces the following result −
Value before change
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
42
vals[3] = 24.1
vals[4] = 50
Value after change
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

Inline Functions in C++


Inline function is a function that is expanded in line when it is called. When the inline function
is called whole code of the inline function gets inserted or substituted at the point of inline
function call.

syntax :
inline return-type function-name(parameters)
{
// function code
}
Eg:
#include <iostream>
using namespace std;
inline int cube(int s)
{
    return s*s*s;
}
int main()
{
    cout << "The cube of 3 is: " << cube(3) << "\n";
    return 0;
} //Output: The cube of 3 is: 27

Inline functions provide following advantages:


1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal function
calls. Other optimizations can be obtained by considering the flows of calling context and the
called context.

43
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
C++ Recursion

When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.

When any function is called from main(), the memory is allocated to it on the stack. A
recursive function calls itself, the memory for a called function is allocated on top of memory
allocated to calling function and different copy of local variables is created for each function
call. When the base case is reached, the function returns its value to the function by whom it is
called and memory is de-allocated and the process continues.

Syntax

returntype recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion(); //calling recursive function
}

Eg:

#include <stdio.h>

unsigned long long int factorial(unsigned int i) {

if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}

int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

44
Factorial of 12 is 479001600

Function Overloading in C++

Two or more functions can have the same name but different parameters; such functions are
called function overloading.       

In OOP, function overloading is known as a function of polymorphism. The function can


perform various operations best on the argument list. It differs by type or number of
arguments they hold. By using a different number of arguments or different types of
arguments, the function can be redefined.    

Rules of overloading functions

 Functions should have different type of arguments.


 Functions should have a different number .

 Functions should have a different sequence of parameters.

#include <iostream>

using namespace std;

class Addition

public:

int sum(int a,int b)

return a+b;

int sum(int a,int b, int c)

45
return a+b+c;

};

int main(void)

Addition obj;

cout<<obj.sum(20, 15)<<endl;

cout<<obj.sum(81, 100, 10);

return 0;

C++ Mathematical Functions

C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min functions

The max(x,y) function can be used to find the highest value of x and y:

Example
cout << max(5, 10);

And the min(x,y) function can be used to find the lowest value of x and y:

Example
cout << min(5, 10);

C++ <cmath> Header

Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm),


can be found in the <cmath> header file:

46
Example
// Include the cmath library
#include <cmath>

cout << sqrt(64);
cout << round(2.6);
cout << log(2);

Other Math Functions

A list of other popular Math functions (from the <cmath> library) can be found in the table
below:

Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x

cosh(x) Returns the hyperbolic cosine of x

exp(x) Returns the value of Ex

expm1(x) Returns ex -1

fabs(x) Returns the absolute value of a floating x

fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer

hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z) Returns x*y+z without losing precision

fmax(x, y) Returns the highest value of a floating x and y

47
fmin(x, y) Returns the lowest value of a floating x and y

fmod(x, y) Returns the floating point remainder of x/y

pow(x, y) Returns the value of x to the power of y

sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of a double value

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

Class

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

An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.

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.

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

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.

#include <iostream>

using namespace std;

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;

49
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

Member Functions in Classes

There are 2 ways to define a member function:


 Inside class definition
 Outside class definition
To define a member function outside the class definition we have to
To define member function inside class, just include function definition inside the class .
To define member function outside class, define it outside class and use the scope resolution ::
operator along with class name and function name.
The scope operator (::) specifies the class to which the member being defined belongs
Eg:
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
void set_values (int,int);
int area()
{
return width*height;
}
};

void Rectangle::set_values (int x, int y) {


width = x;
height = y;
}

int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}

50
Nesting of member functions
A member function can be called by using its name inside another member function of the same
class called Nesting of member function.

A member function can access not only the public functions but also the private functions of the
class it belongs to.

//program:adding of two object


#include<iostream>
using namespace std;
class add
{
    public:
        void get();
        void display();
};
void add ::get()
{
    cout<<"Enter x and y;
    cin>>x>>y;
    display();  
}
void add ::display()
{
    cout<<"z="<<z;
}
int main()
{
    add ob;
    ob.get();
    ob.display();
    return 0;
}

Arrays within a Class

 Arrays can be declared as the members of a class.


 The arrays can be declared as private, public or protected members of the class.
 To understand the concept of arrays as members of a class, consider this example.

Example:

#include<iostream>

51
const int size=5;

class student

int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};

void student :: getdata ()


{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}

void student :: tot_marks() //calculating total marks


{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;

52
}

void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

Output:
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343

Array of Objects in c++

 Like array of other user-defined data types, an array of type class can also be created.
 The array of type class contains the objects of the class as its individual elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in data type.

Syntax:

class_name array_name [size] ;

include<iostream>
using namespace std;
class books {
  char tit1e [30];
  float price ;
  public:
     void getdata ();
     void putdata ();
};
53
void books :: getdata () {
   cout<<"Title:”;
   cin>>title;
   cout<<"Price:”;
   cin>>price;
}
void books :: putdata () {
   cout<<"Title:"<<title<< "\n";
   cout<<"Price:"<<price<< "\n”;
   const int size=3 ;
}
int main() {
  books book[size] ;
  for(int i=0;i<size;i++) {
    cout<<"Enter details o£ book "<<(i+1)<<"\n";
    book[i].getdata();
}
   for(int i=0;i<size;i++) {
     cout<<"\nBook "<<(i+l)<<"\n";
     book[i].putdata() ;
}
    return 0;
}
The output of the program is
 Enter details of book 1
Title: c++
Price: 325
Enter details of book 2
Title: DBMS
Price:. 455
Enter details of book 3
Title: Java
Price: 255
Book 1
Title: c++
Price: 325
Book 2
Title: DBMS

54
Price: 455
Book 3
Title: Java
Price: 255

C++ Friend Functions

A friend function of a class is a function that is defined outside that class' scope but it has the
right to access all private and protected members of the class.

Friend functions are not member functions of the class

The friend function is declared using the friend keyword inside the body of the class.

Friend Function Syntax:

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

Characteristics of Friend Functions in C++

 The function is not in the ‘scope’ of the class to which it has been declared a
friend.
 It cannot be invoked using the object as it is not in the scope of that class.

 We can invoke it like any normal function of the class.

 Friend functions have objects as arguments.

 It cannot access the member names directly and has to use dot membership
operator and use an object name with the member name.

 We can declare it either in the ‘public’ or the ‘private’ part.

#include <iostream.h>

55
using namespace std;

class Box {
double width;

public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid ) {
width = wid;
}

void printWidth( Box box ) {


cout << "Width of box : " << box.width <<endl;
}

int main() {
Box box;
box.setWidth(10.0);
printWidth( box );

return 0;
}

UNIT-IV

Constructors

 A constructor is a special member function of a class that is called


(executed) whenever we create new objects of that class.
 A constructor will have exact same name as the class.
 It does not have any return type at all, not even void.
 Constructors are very useful for setting initial values for certain
member variables.
 Different types of constructors are default constructor, parametrized
constructor, copy constructor.
C++ Default Constructor

56
A constructor with no parameters is known as a default constructor.

#include <iostream>

using namespace std;

class line
{
public:
void setlength( double len );
double getlength( );
line(); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor


line::line(void)
{
cout << "Object is being created" << endl;
}
void line::setlength( double len )
{
length = len;
}
double line::getlength( )
{
return length;
}

// Main function for the program


int main()
{
line line;

// set line length


line.setlength(6.0);
cout << "Length of line is " << line.getlength() <<endl;

return 0;
}

57
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line is 6

Parameterized Constructor
 Parametrized constructor is a constructor with parameters
where as default constructor does not have any parameter.
 It is used to assign initial value to an object at the time of its
creation.
 It can have one or more parameters to be initialized to an object at
the time of its creation .

#include <iostream>

using namespace std;


class line
{
public:
void setlength( double len );
double getlength( void );
line(double len); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


line::line( double len)
{
cout << "Object is being created, length = " << len << endl;
58
length = len;
}
void line::setlength( double len )
{
length = len;
}
double line::getlength( void )
{
return length;
}

// Main function for the program


int main() {
line line(10.0);

// get initially set length.


cout << "Length of line : " << line.getlength() <<endl;

// set line length again


line.setlength(6.0);
cout << "Length of line : " << line.getlength() <<endl;

return 0;
}
When the above code is compiled and executed, it produces the following
output
Object is being created, length = 10
Length of line : 10
Length of line : 6

Copy constructor

A copy constructor is a member function that initializes an object


using another object of the same class. 

Syntax : 
classname (const classname &old_obj);

59
In C++, a Copy Constructor may be called in the following cases: 
1. When an object of the class is returned by value. 
2. When an object of the class is passed (to a function) by value as an
argument. 
3. When an object is constructed based on another object of the same class. 
4. When the compiler generates a temporary object.

Example :
#include<iostream>
using namespace std;
 
class point
{
private:
     int x, y;
public:
     Point(int x1, int y1) { x = x1; y = y1; }
 
     // Copy constructor
     point(const Point &p1)
{
x = p1.x; y = p1.y;
}
 
     int getx( ) 
           { 
return x;
}
    int gety()  
          { 
return y;
}
};
 
int main()
{
    point p1(10, 15); // Normal constructor is called here

    point p2 = p1; // Copy constructor is called here

 
    // Let us access values assigned by constructors

    cout << " p1.x is " << p1.getX() << " p1.y is " << p1.getY();
    cout << " \n p2.x is " << p2.getX() << " p2.y is " << p2.getY();
 
    return 0;
60
}

Output: 
p1.x is 10 p1.y is 15
p2.x is 10 p2.y is 15

Destructor
 A destructor is a special member function of a class that is
executed whenever an object of its class is deleted.
 When an object of a class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class ,
destructor will be invoked.
 A destructor will have exact same name as the class prefixed with a
tilde (~).
 It does not return a value .
 It does not take any parameters.
 Destructor can be very useful for releasing resources before coming
out of the program like closing files, releasing memories etc.

Example:
 #include <iostream>

 using namespace std;
 class line
 {
 public:
 void setlength( double len );

61
 double getlength( void );
 line(); // This is the constructor declaration
 ~line(); // This is the destructor: declaration

 private:
 double length;
 };

 // Member functions definitions including constructor
 line::line(void)
 {
 cout << "Object is being created" << endl;
 }
 line::~line(void)
 {
 cout << "Object is being deleted" << endl;
 }
 void line::setlength( double len )
 {
 length = len;
 }
 double line::getlength( void )
 {
 return length;
 }

 // Main function for the program
 int main()
 {
 line line;

 // set line length
 line.setlength(6.0);
 cout << "Length of line : " << line.getlength() <<endl;

 return 0;
 }

62
 When the above code is compiled and executed, it produces the
following output
 Object is being created
 Length of line : 6
 Object is being deleted

Overloading (Function and Operator)

In C++ , when we create two or more members having the same name with
different number or type of parameters, it is known as function
overloading.

And when we give special meaning to an existing operators with out


altering its basic meaning , it is called as operator overloading .

In C++, we can overload:

o methods,
o constructors, and
o indexed properties

Types of overloading in C++ are:


o Function overloading
o Operator overloading

63
C++ Function Overloading
 Function Overloading is defined as the process of having two or more
function with the same name, but different in parameters
 The advantage of Function overloading is that it increases the readability of
the program.

Example :

1. #include <iostream>    
2. using namespace std;    
3. class  cal 
4. {    
5.     public:    
6. static int add(int a,int b)
7. {      
8.         return a + b;      
9.     }      
10. static int add(int a, int b, int c)      
11.     {      
12.         return a + b + c;      
13.     }      
14. };     
64
15. int main(void) 
16. {    
17.     cal  obj1;                                                    //     class object declaration.   
18.     cout<<obj1.add(10, 20)<<endl;      
19.     cout<<obj1.add(12, 20, 23);     
20.    return 0;    
21. }    

Output:
30
55

C++ Operators Overloading


 Operator overloading is a compile-time polymorphism in which the
operator is overloaded to provide the special meaning to the user-
defined data type.
 Operator overloading is used to overload or redefines most of the
operators available in C++.

 It is used to perform the operation on the user-defined data type.

 Advantage of Operators overloading is to perform different operations on the


same operand.

Operator that cannot be overloaded are as follows:

o Scope resolution operator (::)


65
o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading

1. return_type  class_name  : : operator  op(argument_list)  


2. {  
3.      // body of the function.  
4. }  

Rules for Operator Overloading


o Existing operators can only be overloaded, but the new operators
cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-
defined data type.
o We cannot use friend function to overload certain operators.
However, the member function can be used to overload those
operators.
o When unary operators are overloaded through a member function
take no explicit arguments, but, if they are overloaded by a friend
function, takes one argument.
o When binary operators are overloaded through a member function
takes one explicit argument, and if they are overloaded through a
friend function takes two explicit arguments.

Unary operator overloading


Unary operators operate on a single operand and it can be overloaded in C++ .

66
The following operator can be overloaded :

1. increment (++) and decrement (--) operators.

2. unary minus (-) operator.

3. logical not (!) operator

Example : ( ++ unary operator overloading )

1. #include <iostream>    
2. using namespace std;    
3. class test    
4. {    
5.    private:    
6.       int  num;    
7.    public:    
8.        test( )
9. {
10.  num=8
11. }    
12.        void operator ++( )         
13. {     
14.           num = num+2;     
15.        }    
16.        void  print() 
17. {     
18.            cout<<"The Count is: "<<num;     
19.        }    
20. };    
21. int main( )    
22. {    
23.     test tt;    
24.     ++tt;  // calling of a function "void operator ++()"    
67
25.     tt.print();    
26.     return 0;    
27. }    

Output:
The Count is: 10

Binary operator overloading

Binary operators take two arguments and following binary operators like
addition (+) operator, subtraction (-) operator and division (/) operator can
be overloaded in c++;

Syntax:

return_type::operator binary_operator_symbol(parameters)
{
// function definition
}

Example :

class complex
{
int a, b;
public:

void get_data()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
68
}

complex operator+(complex ob)// overaloded operator


function +
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}

void display()

{
cout << a << "+" << b << "i" << "\n";
}
};

main()
{

complex obj1, obj2, result;

obj1.get_data();
obj2.get_data();

result = obj1 + obj2;

cout << "Input Values:\n";


obj1.display();
obj2.display();

cout << "Result:";


result.display();
}
Output

69
Enter the value of Complex Numbers a, b
3 2
Enter the value of Complex Numbers a, b
2 2
Input Values
3 + 2i
2 + 2i
Result
5 + 4i

Type Conversion
 C++ allows us to convert data of one type to that of another. This is known
as type conversion.

 There are two types of type conversion in C++.

1. Implicit Conversion

2. Explicit Conversion (also known as Type Casting)

1. Implicit Type Conversion

The type conversion that is done automatically done by the compiler is known as
implicit type conversion. This type of conversion is also known as automatic
conversion.

Example :

Conversion of int to double

70
#include <iostream>
using namespace std;

int main() {
// assigning an int value to num_int
int num_int = 9;

// declaring a double type variable


double num_double;

// implicit conversion
// assigning int value to a double variable
num_double = num_int;

cout << "num_int = " << num_int << endl;


cout << "num_double = " << num_double << endl;

return 0;
}

Output

num_int = 9
num_double = 9

C++ Explicit Conversion


When the user manually changes data from one type to another, this is known
as explicit conversion. This type of conversion is also known as type
casting.
71
There are three major ways in which we can use explicit conversion in C++.
They are:

1.C-style type casting (also known as cast notation)


2.Function notation (also known as old C++ style type casting)
3.Type conversion operators

C-style Type Casting

As the name suggests, this type of casting is favored by the C


programming language. It is also known as cast notation.
The syntax for this style is:

(data_type)expression;

Eg:

// initializing int variable


int num_int = 26;

// declaring double variable


double num_double;

// converting from int to double


num_double = (double)num_int;

72
Function-style Casting

We can also use the function like notation to cast data from one
type to another.

The syntax for this style is:

data_type(expression);

For example,

// initializing int variable


int num_int = 26;

// declaring double variable


double num_double;

// converting from int to double


num_double = double(num_int);

Eg: Type Casting

#include <iostream>

using namespace std;

int main() {

73
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;

// C-style conversion from double to int


int num_int1 = (int)num_double;
cout << "num_int1 = " << num_int1 << endl;

// function-style conversion from double to int


int num_int2 = int(num_double);
cout << "num_int2 = " << num_int2 << endl;

return 0;
}

Output

num_double = 3.56
num_int1 = 3
num_int2 = 3

Unit- IV

74
Constructors and Destructors: Constructors - Parameterized Constructor - Copy constructor –
Destructors

Operator Overloading and Type Conversion: Defining operator overloading - Overloading unary
operators – Overloading binary operators – Rules for operator overloading – Type conversion

75

You might also like