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

Module-2

Module 2 covers control statements and functions in C++, including various types of if statements, switch statements, loops (for, while, do-while), and the concept of functions. It explains how to use these constructs with examples, demonstrating their syntax and output. Additionally, it discusses the advantages of functions, types of functions, and the difference between call by value and call by reference.
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)
2 views

Module-2

Module 2 covers control statements and functions in C++, including various types of if statements, switch statements, loops (for, while, do-while), and the concept of functions. It explains how to use these constructs with examples, demonstrating their syntax and output. Additionally, it discusses the advantages of functions, types of functions, and the difference between call by value and call by reference.
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/ 42

Module 2 – Control Statements & Functions

DAYANANDA SAGAR COLLEGE OF ENGINEERING


Shavige Malleshwara Hills, Kumaraswamy Layout, Bengaluru-560078
(An Autonomous Institution affiliated to VTU, Belagavi)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Module-2
C++ if-else

In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.

• if statement
• if-else statement
• nested if statement
• if-else-if ladder

C++ IF Statement

The C++ if statement tests the condition. It is executed if condition is true.

if(condition){
//code to be executed
}

C++ If Example

Department of CSE, DSCE Page 1


Module 2 – Control Statements & Functions

#include <iostream>
using namespace std;

int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

Output:/p>

It is even number

C++ IF-else Statement

The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Department of CSE, DSCE Page 2


Module 2 – Control Statements & Functions

If-else Example
#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

Output:

It is odd number

C++ If-else Example: with input from user

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;

Department of CSE, DSCE Page 3


Module 2 – Control Statements & Functions

}
Output:
Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

C++ IF-else-if ladder Statement

The C++ if-else-if ladder statement executes one condition from multiple statements.

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Department of CSE, DSCE Page 4


Module 2 – Control Statements & Functions

C++ If else-if Example

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{

Department of CSE, DSCE Page 5


Module 2 – Control Statements & Functions

cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number

C++ switch

The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.

switch(expression){
case value1:

Department of CSE, DSCE Page 6


Module 2 – Control Statements & Functions

//code to be executed;
break;
case value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;
break;
}

C++ Switch Example


#include <iostream>
using namespace std;

Department of CSE, DSCE Page 7


Module 2 – Control Statements & Functions

int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}
Output:
Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

C++ For Loop

The C++ for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.

for(initialization; condition; incr/decr){


//code to be executed
}

Department of CSE, DSCE Page 8


Module 2 – Control Statements & Functions

Flowchart:

C++ For Loop Example


#include <iostream>
using namespace std;
int main() {
for(int i=1;i<=10;i++){
cout<<i <<"\n";
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Department of CSE, DSCE Page 9


Module 2 – Control Statements & Functions

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner
loop is executed fully when outer loop is executed one time. So if outer loop and inner loop
are executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total 16
times.
C++ Nested For Loop Example

Let's see a simple example of nested for loop in C++.

#include <iostream>
using namespace std;

int main () {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}

Output:

11
12
13
21
22
23
31
32
33
C++ Infinite For Loop

If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.

#include <iostream>

Department of CSE, DSCE Page 10


Module 2 – Control Statements & Functions

using namespace std;

int main () {
for (; ;)
{
cout<<"Infinitive For Loop";
}
}

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c
C++ While loop
In C++, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.
while(condition){
//code to be executed
}

Flowchart:

Department of CSE, DSCE Page 11


Module 2 – Control Statements & Functions

C++ While Loop Example

Let's see a simple example of while loop to print table of 1.

#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}

Output:

1
2
3
4
5
6
7
8
9
10

C++ Nested While Loop Example

In C++, we can use while loop inside another while loop, it is known as nested while loop. The
nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

Department of CSE, DSCE Page 12


Module 2 – Control Statements & Functions

#include <iostream>
using namespace std;
int main () {
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
cout<<i<<" "<<j<<"\n";
j++;
}
i++;
}
}

Output:

11
12
13
21
22
23
31
32
33

C++ Infinitive While Loop Example:

We can also create infinite while loop by passing true as the test condition.

#include <iostream>
using namespace std;

Department of CSE, DSCE Page 13


Module 2 – Control Statements & Functions

int main () {
while(true)
{
cout<<"Infinitive While Loop";
}
}

Output:

Infinitive While Loop


Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop

C++ Do-While Loop

The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.

The C++ do-while loop is executed at least once because condition is checked after loop body.

do{
//code to be executed
}while(condition);

Flowchart:

Department of CSE, DSCE Page 14


Module 2 – Control Statements & Functions

C++ do-while Loop Example

Let's see a simple example of C++ do-while loop to print the table of 1.

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}

Output:

1
2
3
4
5

Department of CSE, DSCE Page 15


Module 2 – Control Statements & Functions

6
7
8
9
10
C++ Nested do-while Loop

In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while
loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
int j = 1;
do{
cout<<i<<"\n";
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}

Output:
11
12
13
21
22
23
31
32

Department of CSE, DSCE Page 16


Module 2 – Control Statements & Functions

33

C++ Infinitive do-while Loop

In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

do{
//code to be executed
}while(true);

C++ Infinitive do-while Loop Example

#include <iostream>
using namespace std;
int main() {
do{
cout<<"Infinitive do-while Loop";
} while(true);
}

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop

C++ Functions

The function in C++ language is also known as procedure or subroutine in other programming
languages.

To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.

Advantage of functions in C

There are many advantages of functions.

Department of CSE, DSCE Page 17


Module 2 – Control Statements & Functions

1) Code Reusability

By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is repetition
of code.

But if you use functions, you need to write the logic only once and you can reuse it several
times.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as
ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++ programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes the
code.

Declaration of a function

The syntax of creating function in C++ language is given below:

Department of CSE, DSCE Page 18


Module 2 – Control Statements & Functions

return_type function_name(data_type parameter...)


{
//code to be executed
}

C++ Function Example

Let's see the simple example of C++ function.

#include <iostream>
using namespace std;
void func() {
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();
}

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Call by value and call by reference in C++

There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

Department of CSE, DSCE Page 19


Module 2 – Control Statements & Functions

Let's understand call by value and call by reference in C++ language one by one.

Call by value in C++

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().

Let's try to understand the concept of call by value in C++ language by the example given
below:

#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);

Department of CSE, DSCE Page 20


Module 2 – Control Statements & Functions

cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}

Output:

Value of the data is: 3

Call by reference in C++

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in C++ language by the example given
below:

#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;

Department of CSE, DSCE Page 21


Module 2 – Control Statements & Functions

cout<<"Value of y is: "<<y<<endl;


return 0;
}

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by reference in C++

No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the


function

2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also

3 Actual and formal arguments will be created Actual and formal arguments will be
in different memory location created in same memory location

INLINE FUNCTIONS

One of the key features of C++ is the inline function. Therefore, let's first examine the
utilization of inline functions and their intended application. If make a function is inline, then
the compiler replaces the function calling location with the definition of the inline function at
compile time.

Any changes made to an inline function will require the inline function to be recompiled again
because the compiler would need to replace all the code with a new code; otherwise, it will
execute the old functionality.

In brief, When the program executes a function call instruction, the CPU copies the function's
arguments to the stack, caches the memory address of the next instruction and then hands
control to the targeted function. The CPU then performs the function's code, saves the return
value in a designated memory address or register, and hands control back to the function that
is called the function. This may become overhead if the function's execution time is shorter
than the time required to move from the calling function to the called function (callee). The
overhead of the function call is typically negligible compared to the length of time required to
run large or complicated functions. The time needed to call a small, frequently used function,
however, is often far longer than the time necessary to run the function's code. Due to the fact

Department of CSE, DSCE Page 22


Module 2 – Control Statements & Functions

that their execution time is less than switching time, tiny functions experience this overhead.
To minimize the overhead of function calls, C++ offers inline functions. When a function is
invoked, it expands in line and is known as an inline function. When an inline function is
invoked, its entire body of code is added or replaced at the inline function call location. At
compile time, the C++ compiler makes this substitution. Efficiency may be increased by inline
function if it is tiny. To the compiler, inlining is merely a request; it is not a command. The
compiler may reject the inlining request. The compiler may not implement inlining in situations
like these:

1. If a function contains a loop. (for, while, do-while)


2. if a function has static variables.
3. Whether a function recurses.
4. If the return statement is absent from the function body and the return type of the
function is not void.
5. Whether a function uses a goto or switch statement.

Syntax for an inline function:

return_type function_name(parameters)
{
// function code?
}

Let's understand the difference between the normal function and the inline function.

Inside the main() method, when the function fun1() is called, the control is transferred to the
definition of the called function. The addresses from where the function is called and the
definition of the function are different. This control transfer takes a lot of time and increases
the overhead.

When the inline function is encountered, then the definition of the function is copied to it. In
this case, there is no control transfer which saves a lot of time and also decreases the overhead.

Let's understand through an example.

#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}

Department of CSE, DSCE Page 23


Module 2 – Control Statements & Functions

int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;

Once the compilation is done, the code would be like as shown as below:

#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}

Why do we need an inline function in C++?

The main use of the inline function in C++ is to save memory space. Whenever the function is
called, then it takes a lot of time to execute the tasks, such as moving to the calling function. If
the length of the function is small, then the substantial amount of execution time is spent in
such overheads, and sometimes time taken required for moving to the calling function will be
greater than the time taken required to execute that function.

The solution to this problem is to use macro definitions known as macros. The preprocessor
macros are widely used in C, but the major drawback with the macros is that these are not
normal functions which means the error checking process will not be done during the
compilation.

C++ has provided one solution to this problem. In the case of function calling, the time for
calling such small functions is huge, so to overcome such a problem, a new concept was
introduced known as an inline function. When the function is encountered inside the main()
method, it is expanded with its definition thus saving time.

We cannot provide the inlining to the functions in the following circumstances:

• If a function is recursive.

Department of CSE, DSCE Page 24


Module 2 – Control Statements & Functions

• If a function contains a loop like for, while, do-while loop.


• If a function contains static variables.
• If a function contains a switch or go to statement

Default arguments
A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the calling function doesn’t provide a value for the argument. In
case any value is passed, the default value is overridden.
The following is a simple C++ example to demonstrate the use of default arguments. Here,
we don’t have to write 3 sum functions; only one function works by using the default
values for 3rd and 4th arguments.

#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default
values to z,w as 0
{
return (x + y + z + w);
}

// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;

// Statement 2
cout << sum(10, 15, 25) << endl;

// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}

Output
25
50
80

Department of CSE, DSCE Page 25


Module 2 – Control Statements & Functions

C++ Object and Class

Since C++ is an object-oriented language, program is designed using objects and classes in
C++.

In C++, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behaviour. Here, state means data and
behaviour means functionality. Object is a runtime entity, it is created at runtime. Object is an
instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object of student class using s1 as the reference variable.

1. Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class.

C++ Class

In C++, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}

C++ Object and Class Example

Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

#include <iostream>
using namespace std;

Department of CSE, DSCE Page 26


Module 2 – Control Statements & Functions

class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}

Output:

201
Sonoo Jaiswal

C++ Class Example: Initialize and Display data through method

Let's see another example of C++ class where we are initializing and displaying object through
method.

#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{

Department of CSE, DSCE Page 27


Module 2 – Control Statements & Functions

cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}

Output:

201 Sonoo
202 Nakul

C++ Class Example: Store and Display Employee Information

Let's see another example of C++ class where we are storing and displaying employee
information using method.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()

Department of CSE, DSCE Page 28


Module 2 – Control Statements & Functions

{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(201, "Sonoo",990000);
e2.insert(202, "Nakul", 29000);
e1.display();
e2.display();
return 0;
}

Output:

201 Sonoo 990000


202 Nakul 29000
C++ Constructor

In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in
C++ has the same name as class or structure.

In brief, A particular procedure called a constructor is called automatically when an object is


created in C++. In general, it is employed to create the data members of new things. In C++,
the class or structure name also serves as the constructor name. When an object is completed,
the constructor is called. Because it creates the values or gives data for the thing, it is known
as a constructor.

The Constructors prototype looks like this:

1. <class-name> (list-of-parameters);

The following syntax is used to define the class's constructor:

1. <class-name> (list-of-parameters) { // constructor definition }

The following syntax is used to define a constructor outside of a class:

1. <class-name>: :<class-name> (list-of-parameters){ // constructor definition}

Department of CSE, DSCE Page 29


Module 2 – Control Statements & Functions

Constructors lack a return type since they don't have a return value.

There can be two types of constructors in C++.

• Default constructor
• Parameterized constructor

C++ Default Constructor

A constructor which has no argument is known as default constructor. It is invoked at the time
of creating object.

Let's see the simple example of C++ default Constructor.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to provide


different values to distinct objects.

Department of CSE, DSCE Page 30


Module 2 – Control Statements & Functions

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Em
ployee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

What distinguishes constructors from a typical member function?

1. Constructor's name is the same as the class's

Department of CSE, DSCE Page 31


Module 2 – Control Statements & Functions

2. Default There isn't an input argument for constructors. However, input arguments are
available for copy and parameterized constructors.
3. There is no return type for constructors.
4. An object's constructor is invoked automatically upon creation.
5. It must be shown in the classroom's open area.
6. The C++ compiler creates a default constructor for the object if a constructor is not
initialized.

What are the characteristics of a constructor?

1. The constructor has the same name as the class it belongs to.
2. Although it is possible, constructors are typically declared in the class's public section.
However, this is not a must.
3. Because constructors don't return values, they lack a return type.
4. When we create a class object, the constructor is immediately invoked.
5. Overloaded constructors are possible.
6. Declaring a constructor virtual is not permitted.
7. One cannot inherit a constructor.
8. Constructor addresses cannot be referenced to.
9. When allocating memory, the constructor makes implicit calls to the new and delete
operators.

What is a copy constructor?

A member function known as a copy constructor initializes an item using another object from
the same class-an in-depth discussion on Copy Constructors.

Every time we specify one or more non-default constructors (with parameters) for a class, we
also need to include a default constructor (without parameters), as the compiler won't supply
one in this circumstance. The best practice is to always declare a default constructor, even
though it is not required.

A reference to an object belonging to the same class is required by the copy constructor.

Sample(Sample &t)
{
id=t.id;
}

Department of CSE, DSCE Page 32


Module 2 – Control Statements & Functions

What is a destructor in C++?

An equivalent special member function to a constructor is a destructor. The constructor creates


class objects, which are destroyed by the destructor. The word "destructor," followed by the
tilde () symbol, is the same as the class name. You can only define one destructor at a time.
One method of destroying an object made by a constructor is to use a destructor. Destructors
cannot be overloaded as a result. Destructors don't take any arguments and don't give anything
back. As soon as the item leaves the scope, it is immediately called. Destructors free up the
memory used by the objects the constructor generated. Destructor reverses the process of
creating things by destroying them.

The language used to define the class's destructor

~ <class-name>()
{
}

The language used to define the class's destructor outside of it

<class-name>: : ~ <class-name>(){}

C++ Destructor

A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is prefixed
with a tilde sign (~).

C++ Constructor and Destructor Example

Let's see an example of constructor and destructor in C++ which is called automatically.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}

Department of CSE, DSCE Page 33


Module 2 – Control Statements & Functions

~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked

C++ this Pointer

In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C++.

• It can be used to pass current object as a parameter to another method.


• It can be used to refer current class instance variable.
• It can be used to declare indexers.

C++ this Pointer Example

Let's see the example of this keyword in C++ that refers to the fields of current class.

#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)

Department of CSE, DSCE Page 34


Module 2 – Control Statements & Functions

string name; //data member(also instance variable)


float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee

Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee


e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000

C++ static

In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.

Advantage of C++ static keyword

Department of CSE, DSCE Page 35


Module 2 – Control Statements & Functions

Memory efficient: Now we don't need to create instance for accessing the static members, so
it saves memory. Moreover, it belongs to the type, so it will not get memory each time when
instance is created.

C++ Static Field

A field which is declared as static is called static field. Unlike instance field which gets memory
each time whenever you create object, there is only one copy of static field created in the
memory. It is shared to all the objects.

It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.

C++ static field example

Let's see the simple example of static field in C++.

#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
}
};
float Account::rateOfInterest=6.5;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Employee
Account a2=Account(202, "Nakul"); //creating an object of Employee

Department of CSE, DSCE Page 36


Module 2 – Control Statements & Functions

a1.display();
a2.display();
return 0;
}

Output:

201 Sanjay 6.5


202 Nakul 6.5

C++ static field example: Counting Objects

Let's see another example of static keyword in C++ which counts the objects.

#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Account
Account a2=Account(202, "Nakul");
Account a3=Account(203, "Ranjana");

Department of CSE, DSCE Page 37


Module 2 – Control Statements & Functions

a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}

Output:

201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3

C++ Friend function

If a function is defined as a friend function in C++, then the protected and private data of a
class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.

Declaration of friend function in C++

class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};

n the above declaration, the friend function is preceded by the keyword friend. The function
can be defined anywhere in the program like a normal C++ function. The function definition
does not use either the keyword friend or scope resolution operator.

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.

Department of CSE, DSCE Page 38


Module 2 – Control Statements & Functions

o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.

C++ friend function Example

Let's see the simple example of C++ friend function used to print the length of a box.

#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)

{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Output:
Length of box: 10

Let’s see a simple example when the function is friendly to two classes.

#include <iostream>
using namespace std;
class B; // forward declarartion.

Department of CSE, DSCE Page 39


Module 2 – Control Statements & Functions

class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;

Department of CSE, DSCE Page 40


Module 2 – Control Statements & Functions

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function can
access the private members of both the classes A and B.

C++ Friend class

A friend class can access both private and protected members of the class in which it has been
declared as friend.

Let's see a simple example of a friend class.

#include <iostream>

using namespace std;

class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;

Department of CSE, DSCE Page 41


Module 2 – Control Statements & Functions

B b;
b.display(a);
return 0;
}

Output:

value of x is : 5

In the above 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.

Department of CSE, DSCE Page 42

You might also like