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

OOP UNIT 1 & UNIT 2

The document provides comprehensive notes on Object-Oriented Programming (OOP) using C++, covering fundamental concepts such as classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It also details the structure of a C++ program, including sections like documentation, linking, definition, global declaration, function definition, and the main function, along with an overview of data types in C++. Additionally, it explains variable declaration, expressions, and various data types including built-in, user-defined, and derived types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

OOP UNIT 1 & UNIT 2

The document provides comprehensive notes on Object-Oriented Programming (OOP) using C++, covering fundamental concepts such as classes, objects, data abstraction, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. It also details the structure of a C++ program, including sections like documentation, linking, definition, global declaration, function definition, and the main function, along with an overview of data types in C++. Additionally, it explains variable declaration, expressions, and various data types including built-in, user-defined, and derived types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

VELAMMAL ENGINEERING COLLGE

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

21IT201T – OBJECT ORIENTED PROGRAMMING

NOTES

PREPARED BY,

A.JAYANTHI

1
UNIT I

BASICS OF OOPS WITH C++

Overview of OOP concepts , Structure of a C++ program, Data types, Declaration of variables,
Expressions, Operators, Operator Precedence, Type conversions, Pointers, Arrays, Strings,
Structures, Flow control statement- if, switch, while, for, do, break, continue, goto statements.
Functions - Scope of variables, Parameter passing, Default arguments, inline functions,
Recursive functions, Pointers to functions. Dynamic memory allocation and de-allocation
operators-new and delete.

1.1 Overview of OOP concepts

Object-Oriented Programming or OOPs refers to languages that use objects in programming.


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.

OOPs Concepts:
1. Class
2. Objects
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
8. Message Passing

1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can
be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are
their properties.

2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. 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. An object has an identity, state, and
behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message
accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark,
Sleep, and Eats.
2
Object

3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car, but he does
not know about how on pressing the accelerator the speed is increasing, he does not know about
the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car.

4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In Encapsulation, the variables or data of a class
are hidden from any other class and can be accessed only through any member function of their
class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section
handles all the sales-related activities and keeps records of all the sales. Now there may arise a
situation when for some reason an official from the finance section needs all the data about sales
in a particular month. In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales section and then request him
to give the particular data. This is what encapsulation is. Here the data of the sales section and
the employees that can manipulate them are wrapped under a single name “sales section”.

5. Inheritance:
3
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When we
write a class, we inherit properties from other classes. So when we create a class, we do not need
to write all the properties and functions again and again, as these can be inherited from another
class that possesses it. Inheritance allows the user to reuse the code whenever possible and
reduce its redundancy.

6. Polymorphism:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.

7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time.

4
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information to be
sent.

1.2 Structure of a C++ program

Documentation Section:

• This section comes first and is used to document the logic of the program that the
programmer going to code.
• It can be also used to write for purpose of the program.
• Whatever written in the documentation section is the comment and is not compiled by the
compiler.
• Documentation Section is optional since the program can execute without them.

Example,

Single line Comment

// Hello world program

Multi line Comment


/* This is a C++ program to find the
factorial of a number
*/

Linking Section:

The linking section contains two parts:


i) Header Files:

5
• 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.
• In order to use such pre-defined elements in a program, an appropriate header must be
included in the program.
• Standard headers are specified in a program through the preprocessor directive #include. In
the below example, the iostream header is used. When the compiler processes the
instruction #include<iostream>, it includes the contents of the stream in the program. This
enables the programmer to use standard input, output, and error facilities that are provided
only through the standard streams defined in <iostream>. These standard streams process
data as a stream of characters, that is, data is read and displayed in a continuous flow.

#include<iostream>
ii) Namespaces:

• A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
• Any user can create separate namespaces of its own and can use them in any other program.
• namespace std contains declarations for cout, cin, endl, etc. statements.
using namespace std;
• Namespaces can be accessed in multiple ways:
• using namespace std;
• using std :: cout;

Definition Section:

• It is used to declare some constants and assign them some value.

e.g. #define MAX 25

Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.

Global Declaration Section:


• Here, the variables and the class definitions which are going to be used in the program are
declared to make them global.
• The scope of the variable declared in this section lasts until the entire program terminates.
• These variables are accessible within the user-defined functions also.

Function Definition Section:


• It contains all the functions which our main functions need.
• Usually, this section contains the User-defined functions.
• This part of the program can be written after the main function but for this, write the
function prototype in this section for the function which for you are going to write code
after the main function.

6
Example:

#include<iostream>
using namespace std;
void display()
{
cout<<”C++ is better that C”;
}
int main()
{
display()
return 0;
}

Main Function:

• The main function tells the compiler where to start the execution of the program. The
execution of the program starts with the main function.
• All the statements that are to be executed are written in the main function.
• The compiler executes all the instructions which are written in the curly
braces {} which encloses the body of the main function.
• Once all instructions from the main function are executed, control comes out of the
main function and the program terminates and no further execution occur.

Example:
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Output:-Hello World!

1.3 Data types

Data types define the type of data a variable can hold, for example an integer variable can hold
integer data, a character type variable can hold character data etc.

Data types in C++ are categorized into three groups: Built-in, user-defined and Derived.

7
1. Built-in / Primitive Data Types: These data types can be used directly by the user to
declare variables. example: int, char, float, bool, etc. Built-in / Primitive data types available in
C++ are:
• Integer: The keyword used for integer data types is int. Integers typically require 2 bytes of
memory space and range from -2147483648 to 2147483647.
• Character: Character data type is used for storing characters. The keyword used for the
character data type is char. Characters typically require 1 byte of memory space and range
from -128 to 127 or 0 to 255.
• Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type is bool.
• Floating Point: Floating Point data type is used for storing single-precision floating-point
values or decimal values. The keyword used for the floating-point data type is float. Float
variables typically require 4 bytes of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double-
precision floating-point values or decimal values. The keyword used for the double floating-
point data type is double. Double variables typically require 8 bytes of memory space.
• void: Void means without any value. void data type represents a valueless entity. A void
data type is used for those function which does not return a value.
• Wide Character: Wide character data type is also a character data type but this data type
has a size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2
or 4 bytes long.

2. User-defined data types : These data types are defined by the user itself. C++ provides the
following user-defined datatypes:
• Class
• Structure
• Union
• Enumeration

8
Class
A class is defined in C++ using keyword class followed by the name of the class. The body of
the class is defined inside the curly brackets and terminated by a semicolon at the end.
Syntax:
class classname
{
Access Specifier:
Data members;
Member functions(){}
};

Example:
class student
{ // The class
public: // Access specifier
int rollno; // Attribute (int variable)
char name[10]; // Attribute (character variable)
};

Structure

A structure is a user-defined data type in C++. A structure is a collection of different datatype


grouped together under a single name.

Syntax:

struct structureName{
datatype member1;
datatype member2;
datatype member3;
.
.
.
datatype memberN;
};

Example:
Struct employee{
char name[10];
int idno;
float salary;
};

9
Union

A union is a type of structure that can be used where the amount of memory used is a key
factor. It is declared by using the keyword “union“.

Syntax:

union unionName{
datatype member1;
datatype member2;
datatype member3;
.
.
.
datatype memberN;
};

Example:
union employee{
char name[10];
int idno;
float salary;
};

Enumeration
Enum is a user-defined types that consist of named integral constants.
• It helps to assign constants to a set of names to make the program easier to read, maintain
and understand.
• An Enumeration is declared by using the keyword “enum“.

#include <iostream>
using namespace std;
enum week { Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };

int main()
{
enum week day;

day = Wed;

cout << day;


10
return 0;
}
Output:
2

3. Derived data type - The data-types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types. The following are derived data types available in C++
• Function
• Array
• Pointers

Function
A function is a block of code or program-segment that is defined to perform a specific well-
defined task. A function is generally defined to save the user from writing the same lines of
code again and again for the same input. All the lines of code are put together inside a single
function and this can be called anywhere required. main() is a default function that is defined
in every program of C++.

Syntax:

functiontype functionname(parameters)

Example:

#include <iostream>
using namespace std;

int max(int x, int y)


{
if (x > y)
return x;
else
return y;
}

int main()
{
int a = 10, b = 20;
int m = max(a, b);
cout << "m is " << m;
return 0;
}

Output:
m is 20

11
Array
An array is a collection of variables of same datatype that are referenced under a common
name.

Syntax:
datatype arrayname[size_of_array];

Example:

#include <iostream>
using namespace std;
int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;

// this is same as arr[1] = 2


arr[3 / 2] = 2;
arr[3] = arr[0];
cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];
return 0;
}

Output:

5 2 -10 5

Pointers

Pointer is a variable that stores the address of another variable.

Syntax: datatype *var_name;


Example: int *ptr; // pointer declaration
*ptr=&a; // pointer initialization

1.4 Declaration of variables

A variable is a name given to a memory location. It is the basic unit of storage in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In C++, all the variables must be declared before use.

Rules For Declaring Variable:

12
1.The name of the variable contain letters, digits, and underscores.
2.The name of the variable are case sensitive (ex Arr and arr both are different variable).
3.The name of the variable does not contain any whitespace and special
characters (ex #,$,%,* etc).
4.All the variable name must begin with a letter of the alphabet or an underscore(_).
5.We cannot used C++ keyword(ex float,double,class)as a variable name.

Syntax:
datatype variable_name;
Example:
int a=10;

1.5 Expression
A combination of variables, constants and operators that represents a computation forms an
expression. The various categories of an expression are,
• Constant expressions: The expressions that comprise only constant values are called
constant expressions. Example: 20, ‘ a‘ and 2/5+30 .
• Integral expressions: The expressions that produce an integer value as output after
performing all types of conversions are called integral expressions. For example, x,
6*x-y and 10 +int (5.0) are integral expressions. Here, x and yare variables of type int.
• Float expressions: The expressions that produce floating-point value as output after
performing all types of conversions are called float expressions. For example, 9.25, x-y
and 9+ float (7) are float expressions. Here, x ‘and yare variables of type float.
• Relational or Boolean expressions: The expressions that produce a bool type value,
that is, either true or false are called relational or Boolean expressions. For example, x
+ y<100, m + n==a-b and a>=b + c are relational expressions.
• Logical expressions: The expressions that produce a bool type value after combining
two or more relational expressions are called logical expressions. For example, x==5
&&m==5 and y>x I I m<=n are logical expressions.
• Bitwise expressions: The expressions which manipulate data at bit level are
called bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions.
• Pointer expressions: The expressions that give address values as output are
called pointer expressions. For example, &x, ptr are pointer expressions. Here, x is a
variable of any type and ptr is a pointer.
• Special assignment expressions: An expression can be categorized further depending
upon the way the values are assigned to the variables.
1. Chained assignment: It is an assignment expression in which the same value
is assigned to more than one variable, using a single statement. For example,
a = (b=20); or a=b=20;

13
2. Embedded assignment: It is an assignment expression, which is enclosed
within another assignment expression. For example,
a=20+(b=30); //equivalent to b=30; a=20+30;.
3. Compound Assignment: It is an assignment expression, which uses a
compound assignment operator that is a combination of the assignment operator with a
binary arithmetic operator. For example,
a + =20; //equivalent to a=a+20;

Example:
#include <iostream>
using namespace std;
int main() {

//constant expression
int a=10;
int b=(5*2)/10;
char c='x';
cout<<a<<endl<<b<<endl<<c<<endl;

// integer expression
int x=10;
int y=x+int(3.0);
cout<<y<<endl;

// float expression
float p=12.5;
float q=p+float(5);
cout<<q<<endl;

//pointer expression
int aa[]={1,2,3,4,5};
int *ptr;
ptr=aa;
ptr=ptr+1;
cout<<*ptr<<endl;

//relational expression
int a1=10;
int b1=20;
int res=(a1>b1);
cout<<res<<endl;

//logical expression
int x1=5;
int y1=3;
14
int z1=4;
cout<<((x1>y1)||(x1>z1))<<endl;

//bitwise expression
int xy=5;
cout<<(xy>>1)<<endl;

//special assignment expression


int l,k;
l=k=10;
l+=10;
int g,h;
g=(h=100)+25;
return 0;
}

OUTPUT:
10
1
x
13
17.5
2
0
1
2

1.6 Operators

Operators are defined as symbols that helps to perform specific mathematical and logical
computations on operands.

For example,

c=a+b;

Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

C++ operators can be classified as


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
8. Special operators
15
1. ARITHMETIC OPERATORS

Arithmetic operators are used to perform arithmetic operations between two operands.

Operators Meaning
+ Addition
- Subtract
* Multiplication
/ Division
% modulo division(remainder)

Example:

#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter any two integers";
cin>>a>>b;
cout<<"a+b"<<(a+b)<<endl;
cout<<"a-b"<<(a-b)<<endl;
cout<<"a*b"<<(a*b)<<endl;
cout<<"a/b"<<(a/b)<<endl;
cout<<"a%b"<<(a%b)<<endl;
return 0;
}

OUTPUT:
Enter any two integers 6 2
a+b=8
a-b=4
a*b=12
a/b=3
a% b=0

2. RELATIONAL OPERATORS
Relational Operators are used to compare the value of two operands and return Boolean true or
false accordingly.

Operators Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
16
!= Not equal to

Example:

#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter a, b values:";
cin>>a>>b;
cout<<"a>b"<<(a>b)<<endl;
cout<<"a>=b"<<(a>=b)<<endl;
cout<<"a<b"<<(a<b)<<endl;
cout<<"a<=b"<<(a<=b)<<endl;
cout<<"a==b"<<(a==b)<<endl;
cout<<"a!=b"<<(a!=b)<<endl;
return 0;
}
OUTPUT:
Enter a, b values:5 9
a>b0
a>=b0
a<b1
a<=b1
a==b0
a!=b1

3.LOGICAL OPERATORS

The logical operators are used primarily in the expression evaluation to make a decision.

Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Example:

#include <iostream>
using namespace std;
int main()
{
int a = 5;
int b = 9;
cout << ((a == 0) && (a > b)) << endl;
cout << ((a == 0) || (a < b)) << endl;
cout << !(a==5) << endl;
return 0;
17
}

OUTPUT:

0
1
0

4.ASSIGNMENT OPERATOR

The assignment expression evaluates the operand on the right side of the operator (=) and places
its value in the variable on the left.

Note: The left operand in an assignment expression must be a single variable.

There are two forms of assignment:


• Simple assignment-ex. a=10;
• Compound assignment- ex. a+=1;a-=1,a*=1,a/=1

5.INCREMENT (++) AND DECREMENT (--) OPERATORS


The operator ++ adds one to its operand where as the operator - - subtracts one from its operand.

Operators Meaning
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement

Example:

#include<iostream>
using namespace std;
int main()
{
int a=1;
int b=5;
++a;
cout<<"a="<<a<<endl;
--b;
cout<<"b="<<b<<endl;
cout<<"a="<<a++<<endl;
cout<<"a="<<a<<endl;
cout<<"b="<<b--<<endl;
cout<<"b="<<b<<endl;
return 0;
}

18
Output:
a=2
b=4
a=2
a=3
b=4
b=3

6.CONDITIONAL OPERATOR OR TERNARY OPERATOR

A ternary operator evaluates the test condition and executes a block of code based on the result
of the condition.

Syntax:

Example:

#include<iostream>
using namespace std;
int main()
{
int a, b,c;
cout<<"Enter a and b values:";
cin>>a>>b;
c=a>b?a:b;
cout<<"largest of a and b is "<<c;
}

Output:

Enter a and b values:1 5


largest of a and b is 5

7. BIT WISE OPERATORS


The bitwise operators perform bit by bit operation on the values of the two operands.

Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive XOR
<< left shift
>> right shift

19
~ one's complement

Example:

// Program to implement left shift and right shift


#include<iostream>
using namespace std;
int main()
{
int x,shift;
cout<<"Enter a number:";
cin>>x;
cout<<"enter now many times to right shift:";
cin>>shift;
x=x>>shift;
cout<<"After right shift:"<<x<<endl;
cout<<"Enter a number:";
cin>>x;
cout<<"enter now many times to left shift:";
cin>>shift;
x=x<<shift;
cout<<"After left shift:"<<x;
return 0;
}

Output:
Enter a number:8
enter now many times to right shift:2
After right shift:2
Enter a number:8
enter now many times to left shift:3
After left shift:64

// Program to implement Bitwise AND, Bitwise OR, Bitwise XOR

#include <iostream>
using namespace std;
int main()
{
// declare variables
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a & b) << endl;
cout << "a | b = " << (a | b) << endl;
cout << "a ^ b = " << (a ^ b) << endl;
cout << "~ a = " << (~ a) << endl;
20
return 0;
}

Output:

a = 12
b = 25
a&b=8
a | b = 29
a ^ b = 21
~ a = -13

8.SPECIAL OPERATORS

a) sizeof operator- It returns the number of bytes occupied by the operand.

Example: int a,b,c;


c=sizeof(a); //here c=2

b) comma operator- The comma operator (represented by the token) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the second operand and
returns this value (and type). It has lowest precedence among the operators.

Example: a=(x=10,y=20,x+y);

c) Scope Resolution operator


Scope:-Visibility or availability of a variable in a program is called as scope. There are two types
of scope.
i)Local scope ii)Global scope
Local scope: visibility of a variable is local to the function in which it is declared.
Global scope: visibility of a variable to all functions of a program.

Scope resolution operator in “::” .


This is used to access global variables if same variables are declared as local and global.

Example:

#include<iostream>
using namespace std;
int a=5;
int main()
{
int a=10;
cout<<"Local a="<<a<<endl;
cout<<"Global a="<<::a<<endl;
return 0;
}

21
Output:
Local a=10
Global a=5

d) dot (.) and arrow (->) Operators:


• Member operators are used to reference individual members of classes, structures, and
unions.
• The dot operator is applied to the actual object.
• The arrow operator is used with a pointer to an object.

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

f) &,* Operator:
• Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
• Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.

g) Insertion (<<) and Extraction (>>) operators:

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used
for input.

Example:

cout<<”Enter n”;
cin>>n;

1.7 Operator Precedence

Operator precedence determines the grouping of terms in an expression. The associativity of an


operator is a property that determines how operators of the same precedence are grouped in the
absence of parentheses.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

22
Example:

#include <iostream>
using namespace std;

int main() {

// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;

// equivalent expression to num1


int num2 = 5 - (17 * 6);

// forcing compiler to evaluate 5 - 17 first


int num3 = (5 - 17) * 6;

cout << "num1 = " << num1 << endl;


cout << "num2 = " << num2 << endl;
cout << "num3 = " << num3 << endl;

return 0;
}

Output:

num1 = -97
num2 = -97
num3 = -72
23
1.8 Type Conversions

• Type conversion is defined as the process of converting one predefined data type into
another.
• Type conversions are of two types,
1. Implicit conversions
2. Explicit conversions also known as typecasting.

1. Implicit Conversions

Implicit conversion, also known as automatic type conversion refers to the type conversion that
is automatically performed by the compiler.
For example, in expression 5 + 4.25, the compiler converts the int into float as float is larger
than int and then performs the addition.
2. Explicit Conversion (Typecasting)

Typecasting refers to the type conversion that is performed explicitly using type cast operator.
In C++, typecasting can be performed by using two different forms ,
data_type (expression) //expression in parentheses
(data_type)expression //data type in parentheses
Example,
float (num)+ 3.5; //num is of int type
In this example, float () acts as a conversion function which converts int to float.
However, this form of conversion cannot be used in some situations. For example,
ptr=int * (x) ;
In such cases, conversion can be done using the second form of typecasting,
ptr=(int*)x;

1.9 Pointers

A pointer is a variable whose value is the address of another variable.

The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the
pointer variable.

Example,

24
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

• The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.

• The only difference between pointers of different data types is the data type of the
variable or constant that the pointer points to.

Using Pointers in C++

a) Define a pointer variable.


b) Assign the address of a variable to a pointer.
c) Finally access the value at the address available in the pointer

This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand.

25
Output:

There are following few important pointer concepts which should be clear to a C++ programmer,

1. Null pointers
C++ supports null pointer, which is a constant with a value of zero defined in several standard
libraries.

26
Output:

The value of ptr is 0

2. Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --, +, -

3. Pointers vs. Arrays


There is a close relationship between pointers and arrays.

4. Array of Pointers
Arrays can be defined to hold a number of pointers.

5. Pointer to Pointer
C++ allows you to have pointer on a pointer and so on.

6. Passing pointers to functions


Passing an argument by reference or by address both enable the passed argument to be changed
in the calling function by the called function.

7. Return pointer from functions


C++ allows a function to return a pointer to local variable, static variable and dynamically
allocated memory.

1.10 Arrays

• Arrays are fixed-size collections consisting of data items of the same type stored in a
contiguous group of memory locations.
• The elements can be referred by giving the array name followed by the particular
element’s position number in square brackets ( [] ).
• The position number is called a subscript or index.

Declaring arrays

Type name [size];

Example:
int c[12]; // c is an array of 12 int values

Accessing array elements:


• To access array elements, index the array name by placing the element's index in square
brackets following the array name.
• For example:

int b [] = {11, 45, 62, 70, 88};


cout << b[0] << endl; //Outputs 11
cout << b[3] << endl; //Outputs 70

27
• Index numbers may also be used to assign a new value to an element.
For example: b[2] = 49;
• This assigns a value of 49 to the array's third element.

Reading array elements from keyboard

• Array elements can be entered from keyboard using cin statement like any other primary
data type variables but inside a loop.

Example:

int marks [10];


for(int i=0;i<10;i++)
{
cin>>marks[i];
}

Arrays in Calculations

• The following code creates a program that uses a for loop to calculate the sum of all
elements of an array.

int arr [5] = {11, 35, 62, 476, 989};


int sum = 0;
for (int x = 0; x < 5; x++)
{
sum += arr[x];
}
cout << sum << endl;

Output:

1573

Multidimensional Arrays

• Arrays that require two subscripts to identify a particular element are called two-
dimensional arrays or 2-D arrays.
• In general, an array with m rows and n columns is called an m-by-n array.

28
Declaring Two Dimensional Arrays

Type array_name[rows][columns];

Example:
int marks[25][7] //marks is a 2D array of 25 rows and 7 columns of int values

Reading array elements from keyboard


• 2D arrays’ elements can be entered from keyboard using cin statement like any other
primary data type variables but using two loops.
Example:

#include<iostream>
using namespace std;
int main()
{
int marks[25][7]; //marks is a 2D array of 25 rows and 7 columns of int values
for(int i = 0; i<25; i++)
{
for(int j = 0; j<7; j++)
{
cin>>[i][j];
}//for j
}//for i
cout<<”Array contents\n”;
for(int i = 0; i<25; i++)
{
for(int j = 0; j<7; j++)
{
cout<<marks[i][j]<<”\t”;
}
cout<<”\n”;
29
}
}//main()

• Multi-dimensional arrays may be initialized by specifying bracketed values for each row.
• Following is an array with 2 rows and 3 columns:

For example:

int x[2][3] = {{2, 3, 4}, {8, 9, 10}};


cout << x[0][2] << endl;

Output:
4

1.11 Strings
The string is an one-dimensional array of characters which is terminated by a null character '\0'.
The C++ compiler automatically places the '\0' at the end of the string when it initializes the
array.

String Declaration and Initialization:

char a[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


(or)
char a[] = "Hello";

Example:

#include <iostream >


using nam espace std;
int main ()
{
char a[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << a << endl;
return 0;
}

Output:
Greeting message: Hello

30
C++ supports a wide range of functions that manipulate null-terminated strings:
1. strcpy s1, s2;
Copies string s2 into string s1.
2. strcat s1, s2;
Concatenates string s2 onto the end of string s1.
3. strlen s1;
Returns the length of string s1.
4. strcmp s1, s2;
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

Example:

#include <iostream >


#include <string>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;
}

Output:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

1.12 Structures

Structure is a user defined data type which allows to combine data items of different kinds.

Syntax:

The ‘struct’ keyword is used to create a structure.

struct structureName{
31
member1;
member2;
member3;
.
.
.
memberN;
};

Accessing Structure Members

• To access any member of a structure, we use the member access operator (.)

Example:

#include<iostream>
using namespace std;
struct person
{
char name[50];
int age;
float salary;
};
int main()
person p1;
cout<<”Enter Full Name: ”;
cin>>p1.name;
cout<<”Enter Age: ”;
cin>>p1.age;
cout<<”Enter Salary: ”;
cin>>p1.salary;
cout<<”\nDisplaying Information.”<<endl;
cout<<”Name:”<<p1.name<<endl;
cout<<”Age:”<<p1.age<<endl;
cout<<”Salary:”<<p1.salary<<endl;
return 0;
}

Output:
Enter Full Name: Rahul
Enter Age: 27
Enter Salary: 3000

Displaying Information.
Name:Rahul
Age:27
Salary:3000

32
1.13 Flow Control Statement

Control statement is a statement which controls flow of execution of the program. Control
statements are classified into following categories,

1.Sequential control statements- Sequential control statements ensures that the instructions(or
statements) are executed in the same order in which they appear in the program. i.e. By default
system executes the statements in the program in sequential order.

2.Conditional control statements- Statements that are executed when a condition is true. These
statements are divided into three categories. They are,
1. Decision making statements
2. Switch case statement
3. Loop control statements

3. Unconditional control statements-Statements that transfers control from on part of the


program to another part unconditionally. Different unconditional statements are
1. goto
2. break
3. continue

2.1 Decision making statements:- These statements are used to control the flow of execution of
a program by making a decision depending on a condition, hence they are named as decision
making statements.
• Decision making statements are of four types
1.Simple if
2.if else
3.nested if else
4.If else ladder

1.Simple if statement: if the test expression is true then if statement executes statements that
immediately follow if.

Syntax:

if(test expression)
{
list of statements;
}

33
Example
/*largest of two numbers*/

#include<iostream>
using namespce std;
int main()
{
int a,b;
cout<<“Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
if(b>a)
cout<<“B is larger than A\n B=”<<b;
return 0;
}

Output:
Enter any two integers: 12 6
A is larger than B
A=12

2. if –else statement
If test expression is true block of statements following if are executed and if test expression is
false then statements in else block are executed.

Syntax:

if (test expression)
{
statement block1;
}
else
{
statement block2;
}

34
Example

/*largest of two numbers*/

#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<”Enter any two integers:”;
cin>>a>>b;
if(a>b)
cout<<“A is larger than B\n A=”<<a;
else
cout<<“B is larger than A\n B=”<<b;
return 0;
}

Output:
Enter any two integers: 12 6
A is larger than B
A=12

3.Nesting of if-else statements


If –else statement placed inside another if else statement

Syntax:
if(condition){
//statement
if(condition){
// statements}
else{
//statements
}
}
35
else{
//statements
}

Example

/*largest of three numbers*/

#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter a,b,c values:";
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
{
cout<<"A ia largest among three numbers\n";
cout"A= "<<a;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"c= "<<c;
}
}
else
{
if(b>c)
36
{
cout<<"B ia largest among three numbers\n";
cout<<"B="<<b;
}
else
{
cout<<"C ia largest among three numbers\n";
cout<<"C="<<c;
}
}
getch();
return 0;
}

Output:
Enter a,b,c values: 12 6 5
A is largest among three numbers
A=12

4. if else ladder
The condition is evaluated from top to bottom if a condition is true the statement associated with
it is executed.
When all the conditions become false then final else part containing default statements will be
executed.

Syntax:
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement n;
else
default statement.
statement-x;

37
Example

#include<iostream>
using namespace std;
void main()
{
int per;
cout<<”Enter percentage:”;
cin>>per;
if(per>=80)
cout<<”Secured Distinction”<<endl;
else if(per>=60)
cout<<”Secured First Division”<<endl;
else if(per>=50)
cout<<”Secured Second Division”<<endl;
else if(per>=40)
cout<<”Secured Third Division”<<endl;
else
cout<<”Fail”<<endl
}

Output:
Enter percentage: 70
Secured First Division

2.2 SWITCH STATEMENT


If for suppose we have more than one valid choices to choose from then we can use switch
statement in place of if statements.

Syntax:

switch(expression)

38
{
case value-1:
block-1
break;
case value-2:
block-2
break;
--------
--------
default:
default block;
}

Example

/*program to simulate a simple calculator */

#include<iostream>
using namespace std;
int main()
{
float a,b;
char opr;
cout<<"Enter number1 operator number2 : ";
cin>>a>>oper>>b;
switch(opr)
{
case '+':
cout<<"Sum : "<<(a + b)<<endl;
39
break;
case '-': cout<<"Difference : "<<(a -b)<<endl;
break;
case '*': cout<<”Product : "<<a * b<<endl;
break;
case '/': cout<<”Quotient :"<<(a / b)<<endl;
break;
default: cout<<”Invalid Operation!"<<endl;
}
return 0;
}

Output:
Enter number1 operator number2 : 5+6
Sum:11

2.3 Loop control statements


A block or group of statements executed repeatedly until some condition is satisfied is called
Loop.
The group of statements enclosed within curly brace is called block or compound statement.
• Loop statements can be divided into three categories,
1.while loop statement
2.do while loop statement
3.for loop statement

1.WHILE STATEMENT

It is an entry controlled loop. The condition is evaluated and if it is true then body of loop is
executed. After execution of body the condition is once again evaluated and if is true body is
executed once again. This goes on until test condition becomes false.

Syntax:

while(test condition)
{
body of the loop
}

40
Example:

/*program to find sum of n natural numbers */

#include<iostream>
using namespace std;
int main()
{
int i = 1,sum = 0,n;
cout<<"Enter N:"<<end;
cin>>n;
while(i<=n)
{
sum = sum + i;
i = i + 1;
}
cout<<”Sum of first”<<n<”natural numbers is:”<<sum<<endl;
return 0;
}

Output:
Enter N: 5
Sum of first 5 natural numbers is:15

2. DO WHILE STATEMENT
The do while is an exit controlled loop and its body is executed at least once.

Syntax:

do
{
body
}while(test condition);

41
Example:

/* Program to find sum of n natural numbers */

#include<iostream>
using namespace std;
int main()
{
int i = 1,sum = 0,n;
cout<<”Enter N:"<<endl;
cin>>n;
do{
sum = sum + i;
i = i + 1;
} while(i<=n);
cout<<”Sum of first”<< n<<” natural numbers is:”<<sum;
return 0;
}

Output:
Enter N: 5
Sum of first 5 natural numbers is:15

3. FOR LOOP
• It is also an entry control loop that provides a more concise structure.
• For statement is divided into three expressions each is separated by semi colon,
1.initilization expression is used to initialize variables
2.test expression is responsible of continuing the loop. If it is true, then the
program control flow goes inside the loop and executes the block of statements
associated with it .If test expression is false loop terminates
3.increment/decrement expression consists of increment or decrement operator
This process continues until test condition satisfies.

Syntax:

for(initialization; test expression; increment/decrement)


{
statements;
}

42
Example:

/* Program to find sum of n natural numbers */

#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
for(i=1;i<=n;i++)
{
sum = sum + i;
}
cout<<“Sum of first”<<n<<” natural numbers is:%d”<<sum;
return 0;
}

Output:
Enter N: 5
Sum of first 5 natural numbers is:15

Nested loops: Writing one loop control statement within another loop control statement is called
nested loop statement.

43
Example:

/*program to print prime numbers upto a given number*/

#include<iostream>
using namespace std;
void main()
{
int n,i,fact,j;
cout<<"enter the number:";
cin>>n;
for(i=1;i<=n;i++)
{
fact=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
cout<<i<<”\t”;
}
}

Output:
Enter the number : 5
235

3. Unconditional control statements

1. goto
goto statement is used for unconditional branching or transfer of the program execution to
the labeled statement.

44
Example:

/* Program to find sum of n natural numbers */

#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;
i++;
if(i<=n)
goto L1;
cout<<“Sum of first “<<n<” natural numbers
is”<<sum; return 0;
}

Output:

Enter N: 5
Sum of first 5 natural numbers is: 15

2. break:-when a break statement is encountered within a loop ,loop is immediately exited and
the program continues with the statements immediately following loop.

Example:

/*Program to find sum of n natural numbers */

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

45
{
int i ,sum = 0,n;
cout<<”Enter N";
cin>>n;
i=1;
L1:
sum = sum + i;
i++;
if(i>n)
break;
goto L1;
cout<<”Sum of first”<<n<<”natural numbers is: ”<<sum;
return 0;
}

Output:

Enter N: 5
Sum of first 5 natural numbers is: 15

3. Continue: It is used to continue the iteration of the loop statement by skipping the statements
after continue statement. It causes the control to go directly to the test condition and then to
continue the loop.

Example:

/*Program to find sum of n positive numbers read from keyboard*/

#include<iostream>
using namespace std;
int main()
{
int i ,sum = 0,n,number;
cout<<Enter N";
cin>>n;
for(i=1;i<=n;i++)
46
{
cout<<“Enter a number:”;
cin>>number;
if(number<0)
continue;
sum = sum + number;
}
cout<<“Sum of”<<n<<” numbers is:”<<sum;
return 0;
}

Output:

Enter N : 5
12467
Sum of 5 numbers is: 20

1.14 Functions
A function is a group of statements that together perform a task.

Need for a function


1. Functions help us in reducing code redundancy.
2. Functions make code modular. Consider a big file having many lines of code. It becomes
really simple to read and use the code if the code is divided into functions.
3. Functions provide abstraction. For example, we can use library functions without worrying
about their internal work.
4. Code reusability is provided.

Function Types

1. User Defined Function

User Defined functions are user-defined blocks of code specially customized to reduce the
complexity of big programs.

2. Library Function

Library functions are also called “builtin Functions“. These functions are a part of a compiler
package that is already defined and consists of a special function with special and different
meanings. For Example: sqrt(),strcat(), etc.

47
Defining a Function:

Syntax:

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:

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

2. Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

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

4. Function Body: The function body contains a collection of statements that define what the
function does.

Example:

int max(int num 1, int num 2)


{
// local variable declaration
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
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.

48
Syntax:
return_type function_name( parameter list );

Example:
int max(int num 1, int num 2);

NOTE: Parameter names are not important in function declaration only their type is required, so
following is also valid declaration,

int max(int, int);

Calling a Function:
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function
ending closing brace is reached, it returns program control back to the main program.

Example:

#include <iostream>
using namespace std;
// function declaration
int max(int num 1, int num 2);
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 num 1, int num 2)
{
// local variable declaration
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}

49
Output:
Max value is : 200

Function Prototype

A function prototype is a declaration of a function that tells the program about the type of value
returned by the function, name of function, number and type of arguments.

The different categories of function prototype are as follows,

i) Function with no return value and no argument.

Example: void add(void);

ii) Function with arguments passed and no return value.

Example: void add(int,int);

iii) Function with no arguments but returns a value.

Example: int add(void);

iv) Function with arguments and returns a value.

Example: int add(int,int);

i) Function with no return value and no argument.

/*program to print square of a number using functions*/

#include<iostream>
using namespace std;
void main()
{
void sqr(void);
sqr();
return 0;
}
void sqr()
{
int no;
cout<<“Enter a no.”;
cin>>no;
cout<<“Square of”<<no<<“is”<<no*no;
}

Output:
50
Enter a no. 5
Square of 5 is 25

ii) Function with arguments passed and no return value.

#include<iostream>
using namespace std;
void add(int,int);
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
return 0;
}
void add(int x,int y)
{
intc;
c=x+y;
cout<<“addition is”<<c;
}

Output:
enter values of a and b 2 3
addition is 5

iii) Function with no arguments but returns a value.

#include<iostream>
using namespace std;
int main()
{
int add(void);
int z;
z=add();
cout<<sum of 2 nos is”<<z;
return 0;
}
int add(void);
{
int a,b;
cout<<“enter 2 nos”;
cin>>a>>b;
return(a+b);
}

51
Output:
enter 2 nos 2 3
sum of 2 nos is 5

iv) Function with arguments and returns a value.

#include<iostream>
using namespace std;
int main()
{
int sqr(int);
int a,ans;
cout<<“enter a number”;
cin>>a;
ans=sqr(a);
cout<<“square of number is”<<ans;
return 0;
}
int sqr(int X)
{
return(X*X);
}

Output:
enter a number 5
square of number is 25

1.15 Scope of Variables


Scope of a variable is its lifetime in the program. This means that the scope of a variable is the
block of code in the entire program where the variable is declared, used, and can be modified.

There are mainly two types of variable scopes:


1. Local Variables
2. Global Variables

1. Local Variables
Variables defined within a function or block are said to be Local Variables. Local variables do
not exist outside the block in which they are declared, i.e. they cannot be accessed or used
outside that block.

Example:

#include<iostream>
using namespace std;
void func()
{
52
int age=18; // local variable and cannot be accessed outside this function
cout<<age;
}

int main()
{
cout<<"Age is: ";
func();

return 0;
}

Output:
Age is: 18

2. Global Variables
Global Variables can be accessed from any part of the program. They are available throughout
the life time of a program. They are declared at the top of the program outside all of the
functions or blocks.
Example:
#include<iostream>
using namespace std;
int x = 0; // Global variable
int main()
{
int y = 10; // Local variable
cout << "Value of global x is " << x;
cout<< "\nValue of local y is " << y;
return 0;
}
Output:
Value of global x is 0
Value of local y is 10

1.16 Parameter Passing


There are different ways in which parameter can be passed into and out of methods and
functions. They are,
1. Actual Parameters
The Actual Parameters are the values that are passed to the function when it is invoked.The
Actual Parameters are passed by calling function. In actual parameters there is no mentioning
of data types. Only the value is mentioned.
2. Formal Parameters

53
The Formal Parameters are the variables defined by the function that receives values when the
function is called. The Formal Parameters are in the called function. In formal parameters, the
data types of the receiving values should be included.

Methods of Parameter Passing

1. Call by value
In call by value method, any changes made to the formal parameter inside the called function
will not be reflected in the actual parameter in the calling function.

Example:

#include<iostream>
using namespace std;
void swap(int ,int );
int main()
{
int a,b;
cout<<"Enter the Two Numbers: ";
cin>>a>>b;
cout<<"\nAfter Swapping of Two Numbers:";
swap(a,b);
return 0;
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
cout<<" "<<x<<" "<<y;
}

Output:
Enter the Two Numbers: 6 8
After Swapping of Two Numbers: 8 6

2. Call by Reference (aliasing)


In call by Reference method, any changes to the formal parameter are reflected in the actual
parameter in the calling function as formal parameter receives a reference (or pointer) to the
actual data.

54
Example:

#include<iostream>
using namespace std;

void swap(int *x ,int *y );


int main()
{

int a,b;
cout<<"Enter Two Numbers To Swap: ";
cin>>a>>b;
swap(&a,&b);
cout<<"\nAfter Swapping Two Numbers: ";
cout<<a<<" "<<b<<" \n";
return 0;
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
}

Output:
Enter Two Numbers To Swap: 8 6
After Swapping Two Numbers: 6 8

1.17 Default Arguments


When a function is defined, a default value can be specified for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function. This
is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default
given value is used, but if a value is specified, this default value is ignored and the passed value
is used instead.

Example:

#include <iostream >


using namespace std;
int sum (int a, int b=20)
{
int result;
55
result = a + b;
return (result);
}
int main ()
{
int a = 100;
int b = 200;
int result;
result = sum (a, b);
cout << "Total value is :" << result << endl;
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}

Output:
Total value is : 300
Total value is : 120

1.18 Inline Functions


• If a function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time. Any change to an inline function could
require all clients of the function to be recompiled because compiler would need to
replace all the code once again otherwise it will continue with old functionality.
• To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
• A function definition in a class definition is an inline function definition, even without
the use of the inline specifier.

Example:

#include <iostream >


using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}

Output:

56
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

1.19 Recursive Functions

The process in which a function calls itself is known as recursion. The purpose of recursion is to
divide the problem into smaller problems till the base condition is reached.

Every recursive solution has two major cases, which are as follows:

• base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.

• recursive case, in which first the problem at hand is divided into simpler sub parts.

For example in the factorial program the factorial function f(n) is solved by calling a smaller
factorial function f(n-1), this happens repeatedly until the n value reaches base condition
(f(1)=1).

Example:

#include <iostream>
using namespace std;
int f(int n)
{
if (n == 0 || n == 1) // Base case
return 1;
else
return n*f(n-1); // Recursive case
}
int main()
{
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"Factorial of entered number: "<<f(num);
return 0;
}

Output:
Enter a number: 5
Factorial of entered number: 120

1.20 Pointers to Functions

57
C++ allows to pass a pointer to a function. To do so, simply declare the function parameter as a
pointer type.

The following is a simple example where we pass integer pointer and an integer variable to a
function and change the value inside the function which reflects back in the calling function,

#include <iostream>
using namespace std;
void salarychange(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
cout<<"Enter the employee current salary:";
cin>>salary;
cout<<"Enter bonus: ";
cin>>bonus;
salarychange(&salary, bonus);
cout<<"Final salary: "<< salary;
return 0;
}

Output:

Enter the employee current salary: 100


Enter bonus: 20
Final salary: 120

The function which can accept a pointer, can also accept an array as shown in the following
example:

#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage(balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;

58
}
double getAverage(int *arr, int size)
{
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}

Output:

Average value is: 214.4

1.21 Dynamic memory allocation and de-allocation operators - new and delete.

C++ supports these functions and also has two operators new and delete, that perform the task
of allocating and freeing the memory in a better and easier way.

new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient
memory is available, a new operator initializes the memory and returns the address of the
newly allocated and initialized memory to the pointer variable.

Syntax to use new operator


pointer-variable = new data-type;

Example:

#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int;
*p=10;
cout<<*p;
return 0;
}

Output:
10

59
Syntax to allocate a block of memory:

pointer_variable = new datatype[size];

Example:

#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int[5];
p[0]=1;
p[1]=2;
p[2]=3;
p[3]=4;
p[4]=5;
for(int i=0;i<5;i++)
{
cout<<p[i]<<" ";
}
return 0;
}

Output:
12345

Delete Operator

Delete operator is used to deallocate dynamically allocated memory.

Syntax:

delete pointer-variable;

Example:

#include<iostream>
using namespace std;
int main()
{
60
int *p;
p=new int;
*p=10;
delete p;
return 0;
}

Syntax to delete the block of allocated memory:


delete[ ] pointer_variable;

Example:

#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int[2];
p[0]=1;
p[1]=2;
delete []p;
return 0;
}

61
UNIT II

C++ CLASSES AND OPERATOR OVERLOADING

Class definition, Class structure, Class objects, Class scope, this pointer, Friends to a class, Static
class members, Constant member functions, Constructors and Destructors – Copy Constructor,
Shallow Copy Vs Deep Copy, Dynamic creation and destruction of objects-new and delete
operator, Operator Overloading Type, Conversions.

2.1 Class Definition

• A Class is a user defined data-type which has data members and member functions
that can be accessed and used by creating an instance of that class.
• Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior of the objects in a Class.
• C++ class is like a blueprint for an object.

2.2 Class Structure

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.

Access Specifier:

Access specifier or access modifiers are the labels that specify type of access given to members
of a class. These are used for data hiding. These are also called as visibility modes. There are
three types of access specifiers,

1.private
2.public
3.protected

62
1.Private:
If the data members are declared as private access then they cannot be accessed from other
functions outside the class. It can only be accessed by the functions declared within the class. It
is declared
by the keyword “private”.

2. Public:
If the data members are declared public access then they can be accessed from other functions
out
side the class. It is declared by the keyword “public”.

3. Protected: Members cannot be accessed from outside the class, however, they can be
accessed in inherited classes.

NOTE:

If no access specifier is specified then it is treated by default as private for class whereas public
for structure type.

Example:

class student
{
private :
int roll;
char name[30];
public:
void get_data()
{
cout<<”Enter roll number and name”:
cin>>roll>>name;
}
void put_data()
{
cout<<”Roll number:”<<roll<<endl;
cout<<”Name :”<<name<<endl;
}
};

2.3 Class Objects

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. To use the data and access
functions defined in the class, we need to create objects.

Syntax:

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

Syntax:

Object-name.function-name(actual arguments);

Example:

#include<iostream>
using namespace std;
class student
{
private:
int roll;
char name[20];
public:
void getdata()
{
cout<<”Enter Roll number:”;
cin>>roll;
cout<<”Enter Name:”;
cin>>name;
}
void putdata()
{
cout<<”Roll no:”<<roll<<endl;
cout<<Name:”<<name<<endl;
}
};
int main()
{
student s;
s.getdata();
s.putdata();
returm 0;
}

Output:
Enter Roll number: 3
Enter Name: Rahul
Roll no: 3
Name: Rahul

2.4 Class Scope

64
Scope:-Visibility or availability of a variable in a program is called as scope. There are two types
of scope.

Scope Resolution Operator :: is used to define a function outside a class.

Syntax:
return type class-name::function-name(argument declaration)
{
function-body
}

Example:

#include<iostream.h>
class rectangle
{
int L,B;
public:
void getdata();
void area();
};
void rectangle::getdata()
{
cout<<”Enter Length of rectangle”;
cin>>L;
cout<<”Enter breadth of rectangle”;
cin>>B;
}
int rectangle::area()
{
return L*B;
}
int main()
{
rectangle r;
r.getdata();
cout<<”Area of rectangle is”<<r.area();
return 0;
}

Output:
Enter Length of rectangle 5
Enter breadth of rectangle 6
Area of rectangle is 30

2.5 this Pointer

• The this pointer holds the address of current object


• this pointer points to the current object of the class.

65
In the following example, we have two data members num and ch. In member function
setvalues() we have two local variables having same name as data members name.
If we want to assign the local variable value to the data members, this pointer is used without
which the compiler won’t know that we are referring to object’s data members.

Example:

#include <iostream>
using namespace std;
class sample
{
private:
int num;
char ch;
public:
void setvalues(int num, char ch)
{
this->num =num;
this->ch=ch;
}
void displayvalues(){
cout<<num<<endl;
cout<<ch;
}
};
int main()
{
sample s;
s.setvalues(100, 'A');
s.displayvalues();
return 0;
}

Output:

100
A

2.6 Friends to a class

A friend class can access private and protected members of other class in which it is declared
as friend.

In this example, class B is declared as a friend inside the class A. Therefore, B is a friend of
class A. Class B can access the private members of class A.
Example:

66
#include<iostream>
using namespace std;
class A
{
int x;
public:

A()
{
x=10;
}
friend class B; //friend class
};

class B
{
public:
void display(A t)
{
cout<<endl<<"The value of x="<<t.x;
}
};

int main()
{
A a;
B b;
b.display(a);
return 0;
}

Output:

The value of x=10

Friend functions

The private members cannot be accessed from outside the class. i.e.… a non member function cannot
have an access to the private data of a class. In C++ a non member function can access private by
making the function friendly to a class. It is declared by using keyword “friend”.

Syntax:
class <class_name>
{
friend <return_type> <function_name>(arguments);
};

67
Example: Find the largest of two numbers using Friend Function

#include<iostream>
using namespace std;
class Largest
{
int a,b,m;
public:
void set_data();
friend void find_max(Largest);
};
void Largest::set_data()
{
cout<<"Enter the First No:";
cin>>a;
cout<<"Enter the Second No:";
cin>>b;
}
void find_max(Largest t)
{
if(t.a>t.b)
t.m=t.a;
else
t.m=t.b;

cout<<"Maximum Number is\t"<<t.m;


}

int main()
{
Largest l;
l.set_data();
find_max(l);
return 0;
}

Output:

Enter the First No: 45


Enter the Second No: 67
Maximum Number is 67

2.7 Static class members

Static Data Members:

68
A data member of a class can be qualified as static. A static member variable has certain
special characteristics:

1. It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
2. Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
3.It is visible only within the class, but its lifetime is the entire program.
4.Static data member is defined by keyword “static”.

Syntax
static data_type data_member_name;
Example:
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount()
{
cout<<"count is"<<count;
}
};
int item::count;
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"After reading data";
a.getcount();
b.getcount();
c.getcount();
return 0;
}

69
Output:
count is 0
count is 0
count is 0
After reading data
count is 3
count is 3
count is 3

Static Member Functions


A member function that is declared static has the following properties:
1. A static function can have access to only other static members (functions or variables)
declared in the same class.
2.A static member function is to be called using the class name (instead of its objects) as
follows: class-name :: function-name;

Example:

#include<iostream>
using namespace std;
class test
{
int code;
static int count;
public:
void setcode()
{
code=++count;
}
void showcode()
{
cout<<”object number”<<code;
}
static void showcount()
{
cout<<”count”<<count;
}
};
int test::count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
70
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}

Output:
count 2
count 3
object number 1
object number 2
object number 3

2.8 CONSTANT MEMBER FUNCTIONS

Constant member functions are those functions which are denied permission to change the
values of the data members of their class. To make a member function constant, the keyword
“const” is appended to the function prototype and also to the function definition header.
Like member functions and member function arguments, the objects of a class can also be
declared as const. An object declared as const cannot be modified and hence, can invoke only
const member functions as these functions ensure not to modify the object.
A const object can be created by prefixing the const keyword to the object declaration. Any
attempt to change the data member of const objects results in a compile-time error.

Syntax:

(i) For function declaration within a class.


<return_type> <function_name>() const

Example:
int get_data() const;
(ii) For function definition within the class declaration.
<return_type> <function_name>() const
{
//function body
}
Example:
int get_data() const
{
//function body
}

71
(iii) For function definition outside the class.
<return_type> <class_name> : : <function_name>() const
{
//function body
}
Example:
int Demo :: get_data() const
{
}
Example Program:

#include<iostream>
using namespace std;

class Demo
{
int x;

public:

void set_data(int a)
{
x=a;
}

int get_data() const //constant member function


{
++x; // Error while attempting to modify the data member
return x;
}

};
int main()
{
Demo d;
d.set_data(10);
cout<<endl<<d.get_data();

return 0;
}

Output:
Error

72
// Example: Constant member function defined outside the class

#include<iostream>
using namespace std;

class Demo
{
int x;

public:

void set_data(int);

int get_data() const;

};

void Demo::set_data(int a)
{
x=a;
}

int Demo::get_data() const


{
return x;
}

int main()
{
Demo d;
d.set_data(10);
cout<<endl<<d.get_data();

return 0;
}

Output:
10

2.9 CONSTRUCTORS AND DESTRUCTORS

• A Constructor is a special member function that is called automatically when an object is


created.
• The purpose of a constructor is to mainly initialize the member variables of a class.
• It is called constructor because it constructs the values of data members of the class.

73
In the above example class declaration, class Sum has a member function Sum( ) with the same
name of the class and which provides initial value to its data members.

Characteristics of Constructor
• The name of the constructor is the same as the name of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• A Constructor, even though it is a function, has no return type, i.e. it is neither a value-
returning function nor a void function.
• The constructor should be declared in the public section.
• Constructors are executed automatically i.e. they are never invoked. They are executed
when a class object is created.
• A class can have more than one constructor. However all constructor of a class should
have the same name.
• It is not possible to refer to the address of the constructors.
• The constructors make implicit calls to the operator new and delete when memory
allocation is required.

Example:

// defining the constructor within the class

#include <iostream>
using namespace std;

class student {
int rno;
char name[10];
double fee;

public:
student()
74
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}

void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};

int main()
{
student s; // constructor gets called automatically when we create the object of the class
s.display();

return 0;
}

Output:
Enter the RollNo: 3
Enter the Name: Rahul
Enter the Fee: 45000
3 Rahul 45000

// defining the constructor outside the class

#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
student();
void display();
};

student::student()
{
cout << "Enter the RollNo:";
cin >> rno;

75
cout << "Enter the Name:";
cin >> name;

cout << "Enter the Fee:";


cin >> fee;
}

void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}

int main()
{
student s;
s.display();

return 0;
}

Output:

Enter the RollNo: 30


Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
Types of Constructors

1. Default constructor
Default Constructor is the constructor which doesn’t take any argument. It has no parameters.
It is also called a zero-argument constructor.

Example:
#include <iostream>
using namespace std;
class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}

76
};

int main()
{
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 0;
}

Output
a: 10
b: 20

2. Parameterized constructor

A constructor that takes one or more arguments is called parameterized constructor.

Example:

#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

77
return 0;
}

Output:
p1.x = 10, p1.y = 15
When an object is declared in a parameterized constructor, the initial values have to be passed
as arguments to the constructor function. The normal way of object declaration may not work.
The constructors can be called explicitly or implicitly.

Example: e = Example(0, 50); // Explicit call


Example: e(0, 50); // Implicit call

3. Copy Constructor

A copy constructor is a member function that initializes an object using another object of the
same class.
Copy constructor takes a reference to an object of the same class as an argument.

// Implicit copy constructor

#include<iostream>
using namespace std;

class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};

int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1;


obj2.display();
return 0;
}

78
Output:
ID=10
ID=10

// Example: Explicit copy constructor


#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor


{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
79
return 0;
}
Output:
ID=10
ID=10
DESTRUCTOR
A destructor is special member function that is executed when an object of that class is
destroyed.
Characteristics of Destructor
• The destructor name must have the same name as the class preceded by a tilde (~).
• The destructor cannot take arguments therefore cannot be overloaded.
• The destructor has no return type.
• There can be only one destructor in each class.
• The destructor cannot be inherited.
• Destructor cannot be declared as static and const;
• Destructor should be declared in the public section of the program.
• Destructor is called in the reverse order of its constructor invocation.

Syntax:

~ <class-name>()
{
}
Example:
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};
int main()
{
Test t;
return 0;
}

80
Output:
Constructor executed
Destructor executed
2.10 SHALLOW COPY VS DEEP COPY
SHALLOW COPY DEEP COPY
1.When we create a copy of object by copying 1.When we create an object by copying data
data of all the member variables as it is, then of another object along with the values of
it is called shallow copy. memory resources that reside outside the
object, then it is called a deep copy.
2.A shallow copy of an object copies all of the 2.Deep copy is performed by implementing
member field values. our own copy constructor.
3.In Shallow copy, the two objects are not 3.It copies all fields, and makes copies of
independent. dynamically allocated memory pointed to by
the fields.
4.It also creates a copy of the dynamically 4. If we do not create the deep copy in a
allocated objects rightful way then the copy will point to the
original, with disastrous consequences.

2.11 DYNAMIC CREATION AND DESTRUCTION OF OBJECTS-NEW AND DELETE


OPERATOR
Example:
#include <iostream>
using namespace std;
class Random
{
public:
Random() {
cout << "Constructor" << endl;
}
~Random() {
cout << "Destructor" << endl;
}
};
int main()
{
Random* a = new Random[3];

81
delete [] a; // Delete array
return 0;
}
Output:
Constructor
Constructor
Constructor
Destructor
Destructor
Destructor
2.12 OPERATOR OVERLOADING

C++ has the ability to provide the operators with a special meaning for a data type, this ability
is known as operator overloading.

Example:

#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}

Output:
12+i9
82

You might also like