0% found this document useful (0 votes)
25 views62 pages

UNIT - I - Final Print

The document provides an introduction to Object-Oriented Programming (OOP) concepts using C++, covering basics such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the history of C++, its standard libraries, and various programming constructs including variables, operators, and input/output operations. Additionally, it highlights the advantages of OOP over procedural programming and includes examples of C++ syntax and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views62 pages

UNIT - I - Final Print

The document provides an introduction to Object-Oriented Programming (OOP) concepts using C++, covering basics such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the history of C++, its standard libraries, and various programming constructs including variables, operators, and input/output operations. Additionally, it highlights the advantages of OOP over procedural programming and includes examples of C++ syntax and operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIT I BASIC CONCEPTS OF OOPS

Introduction of Object Oriented Programming – Characteristics of Object Oriented Languages –


C++ Programming basics - Loops and Decisions – Function Components - Passing Parameters -
Class Specification- Member Function Definition – Constructors – Destructors – C++ objects as
data types – Objects as function arguments - Structures and Classes - Static Class Data – const and
Classes – Inline function

Introduction of Object Oriented Programming

The major purpose of C++ programming is to introduce the concept of object orientation to the C
programming language.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as truly object-
oriented programming language. Smalltalk is considered as the first truly object-oriented
programming language.

Characteristics of Object Oriented Languages

Object Oriented programming is a programming style that is associated with the concept of Class,
Objects and various other concepts revolving around these two, like Inheritance, Polymorphism,
Abstraction, Encapsulation etc.
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.


Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.

Advantage of OOPs over Procedure-oriented programming language

1. OOPs makes development and maintenance easier where as in Procedure-oriented


programming language it is not easy to manage if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.

C++ Programming basics

C++ is an object-oriented programming language. It is an extension to C programming.

Our C++ tutorial includes all topics of C++ such as first example, control statements, objects and
classes, inheritance, constructor, destructor, this, static, polymorphism, abstraction, abstract class,
interface, namespace, encapsulation, arrays, strings, exception handling, File IO, etc.

What is C++

C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.

C++ is a middle-level language, as it encapsulates both high and low level language features.

C++ History

History of C++ language is interesting to know. Here we are going to discuss brief history of C+
+ language.

C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of
AT&T (American Telephone & Telegraph), located in U.S.A.
Bjarne Stroustrup is known as the founder of C++ language.

It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.

Object-Oriented Programming (OOPs)

C++ supports the object-oriented programming, the four major pillar of object-oriented
programming (OOPs) used in C++ are:

1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction

C++ Standard Libraries

Standard C++ programming is divided into three important parts:

o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.

Usage of C++

By the help of C++ programming language, we can develop different types of secured and robust
applications:

o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc

C++ Program

Before starting the abcd of C++ language, you need to learn how to write, compile and run the
first C++ program.

To write the first C++ program, open the C++ console and write the following code:

#include <iostream.h>
#include<conio.h>
void main() {
clrscr();
cout << "Welcome to C++ Programming.";
getch();
}
 #include<iostream.h> includes the standard input output library functions. It
provides cin and cout methods for reading from input and writing to output respectively.
 #include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
 void main() The main() function is the entry point of every program in C++ language.
The void keyword specifies that it returns no value.
 cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
 getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
File: main.cpp

#include <iostream>
using namespace std;
int main()
{
cout << "Hello C++ Programming";
return 0;
}

A detailed explanation of first C++ program is given in next chapters.

C++ Basic Input/Output

C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.

If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.

If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.
I/O Library Header Files

Let us see the common header files used in C++ programming are:

Header Function and Description


File

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard
output stream, standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)

The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console

Let's see the simple example of standard output stream (cout):

#include <iostream>
using namespace std;
int main( )
{
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}

Output:

Value of ary is: Welcome to C++ tutorial


Standard input stream (cin)

The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>)
to read the input from a console.

Let's see the simple example of standard input stream (cin):


#include <iostream>
using namespace std;
int main( )
{
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}

Output:

Enter your age: 22


Your age is: 22
Standard end line (endl)

The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.

Let's see the simple example of standard end line (endl):

#include <iostream>
using namespace std;
int main( )
{
cout << "C++ Tutorial";
cout << " Java"<<endl;
cout << "End of line"<<endl;
}

Output:

C++ Tutorial Java


End of line

C++ Variable

A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

type variable_list;
The example of declaring variable is given below:

int x;
float y;
char z;

Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

int x=5,b=10; //declaring 2 variable of integer type


float f=30.8;
char c='A';

Rules for defining variables

A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:

int a;
int _ab;
int a30;

C++ Keywords

A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of
32 Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
C++ Operators

An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator

1. C++ Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.
Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators


#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;
// printing the division of a by b
cout << "a / b = " << (a / b) << endl;
// printing the modulo of a by b
cout << "a % b = " << (a % b) << endl;
return 0;
}
Output
a+b=9
a-b=5
a * b = 14
a/b=3
a%b=1
Increment and Decrement Operators
C++ also provides increment and decrement operators: ++ and -- respectively.
• ++ increases the value of the operand by 1
• -- decreases it by 1
For example,
int num = 5;

// increment operator
++num; // 6
Here, the code ++num; increases the value of num by 1.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a


result_a = ++a;
cout << "result_a = " << result_a << endl;

// decrementing b by 1 and storing the result in result_b


result_b = --b;
cout << "result_b = " << result_b << endl;

return 0;
}
Output
result_a = 11
result_b = 99
2. C++ Assignment Operators
In C++, assignment operators are used to assign values to variables. For example,

// assign 5 to a
a = 5;

Here, we have assigned a value of 5 to the variable a.


Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;
%= a %= b; a = a % b;

Example 3: Assignment Operators


#include <iostream>
using namespace std;

int main() {
int a, b;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

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


cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}
Output
a=2
b=7

After a += b;
a=9
3. C++ Relational Operators
A relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not.


If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
Operator Meaning Example

== Is Equal To 3 == 5 gives us false


!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

Example 4: Relational Operators


#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
4. C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If the expression
is true, it returns 1 whereas if the expression is false, it returns 0.
Operator Example Meaning

Logical AND.
expression1 &&
&& True only if all the operands
expression2
are true.

Logical OR.
expression1 ||
|| True if at least one of the
expression2
operands is true.

Logical NOT.
! !expression True only if the operand is
false.
In C++, logical operators are commonly used in decision making. To further understand the
logical operators, let's see the following examples,

Suppose,
a=5
b=8
Then,
(a > 3) && (b > 5) evaluates to true
(a > 3) && (b < 5) evaluates to false
(a > 3) || (b > 5) evaluates to true
(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false
!(a < 3) evaluates to true
!(a > 3) evaluates to false
Example 5: Logical Operators
#include <iostream>
using namespace std;
int main() {
bool result;
result = (3 != 5) && (3 < 5); // true
cout << "(3 != 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 < 5); // false
cout << "(3 == 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 > 5); // false
cout << "(3 == 5) && (3 > 5) is " << result << endl;
result = (3 != 5) || (3 < 5); // true
cout << "(3 != 5) || (3 < 5) is " << result << endl;
result = (3 != 5) || (3 > 5); // true
cout << "(3 != 5) || (3 > 5) is " << result << endl;
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;
result = !(5 == 2); // true
cout << "!(5 == 2) is " << result << endl;
result = !(5 == 5); // false
cout << "!(5 == 5) is " << result << endl;
return 0;}
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
Explanation of logical operator program
 (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
 (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 < 5) are 1 (true).
 (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).
 (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 > 5) are 0 (false).
 !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
 !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits. They can only be used
alongside char and int data types.
Operator Description

& Binary AND

| Binary OR

^ Binary XOR
~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

6. Other C++ Operators


Here's a list of some other common operators available in C++. We will learn about them in later
tutorials.

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

string result = (5 > 0) ? "even" :


?: returns value based on the condition
"odd"; // "even"

represents memory address of the


& &num; // address of num
operand

accesses members of struct variables


. s1.marks = 92;
or class objects

used with pointers to access the class


-> ptr->marks = 92;
or struct variables

<< prints the output value cout << 5;

>> gets the input value cin >> num;

C++ Identifiers

C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rules for naming the identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a program which
are given below:

o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.


o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical.
After the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in
second. Therefore, it proves that identifiers are case-sensitive.

Valid Identifiers

The following are the examples of valid identifiers are:

Result
Test2
_sum
power
Invalid Identifiers

The following are the examples of invalid identifiers:

Sum-1 // containing special character '-'.


2data // the first letter is a digit.
break // use of a keyword.

let's look at a simple example to understand the concept of identifiers.

#include <iostream>
using namespace std;
int main()
{
int a;
int A;
cout<<"Enter the values of 'a' and 'A'";
cin>>a;
cin>>A;
cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
return 0;
}
In the above code, we declare two variables 'a' and 'A'. Both the letters are same but they will
behave as different identifiers. As we know that the identifiers are the case-sensitive so both the
identifiers will have different memory locations.

Output

C++ if-else

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

o if statement
o if-else statement
o nested if statement
o 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
#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
}
C++ 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;
}

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
}

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)
{
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:
//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;
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
}

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

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

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

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.

#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++ 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:
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
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
33
C++ Break Statement

The C++ break is used to break loop or switch statement. It breaks the current flow of the program
at the given condition. In case of inner loop, it breaks only inner loop.

jump-statement;
break;

Flowchart:
C++ Break Statement Example

Let's see a simple example of C++ break statement which is used inside the loop.

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

C++ Break Statement with Inner Loop

The C++ break statement breaks inner loop only if you use break statement inside the inner loop.

Let's see the example code:

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

Output:

11
12
13
21
31
32
33
C++ Continue Statement

The C++ continue statement is used to continue loop. It continues the current flow of the program
and skips the remaining code at specified condition. In case of inner loop, it continues only inner
loop.

jump-statement;
continue;
C++ Continue Statement Example
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
} }

Output:

1
2
3
4
6
7
8
9
10

C++ Goto Statement

The C++ goto statement is also known as jump statement. It is used to transfer control to the other
part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example

Let's see the simple example of goto statement in C++.

#include <iostream>
using namespace std;
int main()
{
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18){
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}}

Output:not eligible to vote!

Enter your age:


16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

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.

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.

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute code. But you
can also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():

Declaration of a function

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

return_type function_name(data_type parameter...)


{
//code to be executed
}
Example Explained

 myFunction() is the name of the function

 void means that the function does not have a return value.

 inside the function (the body), add code that defines what the function should do

Call a Function

 Declared functions are not executed immediately. They are "saved for later use", and will
be executed later, when they are called.
 To call a function, write the function's name followed by two parentheses () and a
semicolon ;
 In the following example, myFunction() is used to print a text (the action), when it is
called:

Example
Inside main, call myFunction():
// Create a function
void myFunction()
{
cout << "Function call";
}

int main() {
myFunction(); // call the function
//myFunction();
//myFunction();
return 0;
}
Function Declaration and Definition

A C++ function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)
 Definition: the body of the function (code to be executed)

#include <iostream>
using namespace std;

// Function declaration
void myFunction();

// The main method


int main()
{
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction()
{
cout << "I just got executed!";
}

C++ Function Parameters


Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the
function.

Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:

Syntax
void functionName(parameter1, parameter2, parameter3)

{
// code to be executed
}

Example
void myFunction(string fname)

{
cout << fname << " welcome\n";
}

int main() {
myFunction("Nithish");
myFunction("Kumar");
myFunction("Raja");
return 0;
}

Default Parameter Value

 You can also use a default parameter value, by using the equals sign (=).
 If we call the function without an argument, it uses the default value ("KRCE"):

Example

void myFunction(string country = "KRCE")

{
cout << country << "\n";
}

int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}

Multiple Parameters

Inside the function, you can add as many parameters as you want:

Example

void myFunction(string fname, int age)


{
cout << fname << " Refsnes. " << age << " years old. \n";
}

int main()
{
myFunction("Rose", 3);
myFunction("Jenny", 14);
myFunction("Deepa", 30);
return 0;
}
Return Values
If you want the function to return a value, you can use a data type (such as int, string, etc.) instead
of void, and use the return keyword inside the function:

Example 1

int myFunction(int x)
{
return 5 + x;
}

int main()
{
cout << myFunction(3);
return 0;
}

Example 2
int myFunction(int x, int y)
{
return x + y;
}

int main()
{
cout << myFunction(5, 3);
return 0;
}

Pass By Reference

In the examples, we used normal variables when we passed parameters to a function. You can also
pass a reference to the function. This can be useful when you need to change the value of the
arguments:

Example
void swapNums(int &x, int &y)

{
int z = x;
x = y;
y = z;
}

int main() {
int firstNum = 10;
int secondNum = 20;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

return 0;
}

C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts
from 0. We can store only fixed set of elements in C++ array.

Advantages of C++ Array

o Code Optimization (less code)

o Random Access

o Easy to traverse data

o Easy to manipulate data

o Easy to sort data etc.

C++ Array Types

There are 2 types of arrays in C++ programming:

1. Single Dimensional Array

2. Multidimensional Array

Example

#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 20, 30, 40, 50}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
C++ Multidimensional Array Example

Let's see a simple example of multidimensional array in C++ which declares, initializes and
traverse two dimensional arrays.

#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}

Output:

5 10 0
0 15 20
30 0 10

C++ Pointers

The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.
Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees
etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many usage of pointers in C++ language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.

Symbols used in pointer


Symbol Name Description

& (ampersand Address operator Determine the address of a


sign) variable.

∗ (asterisk sign) Indirection Access the value of an address.


operator

Declaring a pointer

The pointer in C++ language can be declared using ∗ (asterisk symbol).

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

int ∗ p;
int number=30;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}

Output:

Address of number variable is:0x7ffccc8724c4


Address of p variable is:0x7ffccc8724c4
Value of p variable is:30

Member functions in C++


Member Function:

A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. If the member function is defined inside the class definition it
can be defined directly, but if it is defined outside the class, then we have to use the scope
resolution :: operator along with class name along with function name.

1) Member functions defined within the class

Syntax
class className
{
returnType MemberFunction(arguments)
{
//function body
}
....
};

2) Member functions defined outside the class

syntax
class className
{
returnType MemberFunction(arguments);
....
};

returnType className :: function_Name(arg1,arg2,.....argN)


{
function body
}

Types of Member Functions

1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions

1) Simple functions:

These are the basic member function, which doesn’t have any special keyword like static etc as
a prefix.

return_type functionName(parameter_list)
{
function body;
}

2) Static functions:

Static is a keyword which can be used with data members as well as the member functions. A
function is made static by using the static keyword with the function name. These functions
work for the class as whole rather than for a particular object of a class. It can be called using
the object and the direct member access operator. But, its more typical to call a static member
function by itself, using class name and scope resolution :: operator.

A static member function is a special member function, which is used to access only static
data members, any other normal data member cannot be accessed through static member
function. Just like static data member, static member function is also a class function; it is not
associated with any class object.

We can access a static member function with class name, by using following syntax:

class_name:: function_name(perameter);
#include <iostream>

using namespace std;

class Demo
{
private:
//static data members
static int X;
static int Y;

public:
//static member function
static void Print()
{
cout <<"Value of X: " << X << endl;
cout <<"Value of Y: " << Y << endl;
}
};

//static data members initializations


int Demo :: X =10;
int Demo :: Y =20;

int main()
{
Demo OB;
//accessing class name with object name
cout<<"Printing through object name:"<<endl;
OB.Print();

//accessing class name with class name


cout<<"Printing through class name:"<<endl;
Demo::Print();

return 0;
}

3) Const functions:

Declaring a member function with the const keyword specifies that the function is a "read-only"
function that does not modify the object for which it is called. A constant member function
cannot modify any non-static data members or call any member functions that aren't
constant.To declare a constant member function, place the const keyword after the closing
parenthesis of the argument list. The const keyword is required in both the declaration and the
definition.

#include <iostream>
using namespace std;

int main() {
const int myNum = 15;
myNum=20;
cout << myNum;
return 0;
}

#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0)
{
value = v;
}

// We get compiler error if we add a line like "value = 100;"


// in this function.
int getValue()
const
{
return value;
}
};

int main() {
Test t(20);
cout<<t.getValue();
return 0;
}

4) Inline function in C++

If make a function as 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.

Normally, a function call transfers the control from the calling program to the called function.
This process of jumping to the function, saving registers, passing a value to the argument, and
returning the value to the calling function takes extra time and memory.

An inline function is a function that is expanded inline when it is invoked, thus saving time. The
compiler replaces the function call with the corresponding function code, which reduces the
overhead of function calls.

When an inline function is called, the compiler replaces all the calling statements with the
function definition at run-time. Every time an inline function is called, the compiler generates a
copy of the function’s code, in place, to avoid the function call.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code?
}

inline return-type function-name(parameters)


{
// function code
}

Example Program

#include <iostream>
using namespace std;

inline int max_num(int x, int y)


{
return (x > y)? x : y;
}

// Main function for the program


int main()
{
cout << "Greater of ( 40, 50 ) is: " << max_num(40,50) << endl;
cout << "Greater of ( 90, 50 ) is: " << max_num(90,50) << endl;
cout << "Greater of ( -5, 34 ) is: " << max_num(-5,34) << endl;
return 0;
}

Greater of ( 40, 50 ) is: 50


Greater of ( 90, 50 ) is: 90
Greater of ( -5, 34 ) is: 34

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

5) Friend function:

If a function is defined as a friend function then, the private and protected data of a class can be
accessed using the function. The compiler knows a given function is a friend function by the use
of the keyword friend. For accessing the data, the declaration of a friend function should be
made inside the body of the class starting with keyword friend.

Characteristics of member functions:

1) A program can have several classes and they can have member functions with the same
name, Ambiguity is resolved using the scope resolution operator (::)
2) Private members of a class can be accessed by all the members of the class, whereas non-
member functions are not allowed to access.
3) Member functions of the same class can access all other members of their own class without
the use of dot operator.
4) Member functions defined as public act as an interface between the service provider and the
service seeker.
5) Member functions can take default arguments as well.

using namespace std;

class Distance {
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};

int func(Distance d){


//function definition
d.meter=10; //accessing private data from non-member function
return d.meter;
}

int main(){ Distance D;


cout<<"Distace: "<<func(D);
system("pause");
return 0;
}

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.

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

o Default constructor
o 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.
#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

C++ Parameterized Constructor

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


different values to distinct objects.

#include <iostream>
using namespace std;
class Employee
{
public:
int id;
string name;
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, "Kumar", 50000); //creating an object of Employee
Employee e2=Employee(102, "Nithish", 55000);
e1.display();
e2.display();
return 0;
}
Output
101 Kumar 50000
102 Nithish 55000

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++ destructor cannot have parameters.

Destructor rules

1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor and
inserts it into your code.

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

}
Employee(int a)
{
num=a;
cout<<a<<endl;
}

};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2(10);
return 0;
}
Object as a data type
These are also referred to as Non-primitive or Reference Data Type. They are so-called because
they refer to any particular objects. Unlike the primitive data types, the non-primitive ones are
created by the users in C++. Examples include arrays, strings, classes, interfaces etc. When the
reference variables will be stored, the variable will be stored in the stack and the original object
will be stored in the heap. In Object data type although two copies will be created they both will
point to the same variable in the heap, hence changes made to any variable will reflect the change
in both the variables.
Example 1
#include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
// Create an object of MyClass
MyClass obj;
// Access attributes and set values
obj.myNum = 15;
obj.myString = "Some text";
// Print values
cout <<obj.myNum << "\n";
cout << obj.myString;
return 0;
}
Example 2
#include <iostream>
#include <string>
using namespace std;
class Distance
{
private:

int feet;
float inches;
public:
void setdist(int ft,float in)
{
feet=ft;
inches=in;
}
void getdist()
{
cout<<"\n Enter feet: ";
cin>>feet;
cout<<"\n Enter inches: ";
cin>>inches;
}
void showdist()
{
cout<<feet;
cout<<inches;
}
};
int main()
{
Distance dist1,dist2;
dist1.setdist(11,6.25);
dist2.getdist();

cout<<"\n dist1 = ";


dist1.showdist();

cout<<"\n dist2 = ";


dist2.showdist();
cout<<endl;
return 0;

}
Objects as function arguments

The objects of a class can be passed as arguments to member functions as well as nonmember
functions either by value or by reference. When an object is passed by value, a copy of the actual
object is created inside the function. This copy is destroyed when the function terminates.
Moreover, any changes made to the copy of the object inside the function are not reflected in the
actual object. On the other hand, in pass by reference, only a reference to that object (not the
entire object) is passed to the function. Thus, the changes made to the object within the function
are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members
can be accessed inside the function using the object name and the dot operator. However, the data
members of the calling object can be directly accessed inside the function without using the
object name and the dot operator.
#include <iostream>
using namespace std;

class Demo
{
private:
int a;

public:
void set(int x)
{
a = x;
}

void sum(Demo ob1, Demo ob2)


{
a = ob1.a + ob2.a;
}

void print()
{
cout<<"Value of A : "<<a<<endl;
}
};

int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1,d2);

//printing the values


d1.print();
d2.print();
d3.print();

return 0;
}

Output

Value of A : 10
Value of A : 20
Value of A : 30

Above example demonstrate the use of object as a parameter. We are passing d1 and d2 objects as
arguments to the sum member function and adding the value of data members a of both objects
and assigning to the current object’s (that will call the function, which is d3) data member a.

Structure and Class in C++

What is the structure in C++?

A structure is a grouping of variables of various data types referenced by the same name. A
structure declaration serves as a template for creating an instance of the structure.

Syntax:

The syntax of the structure is as follows:

Struct Structurename
{
Struct_member1;
Struct_member2;
Struct_member3;
.
.
.
Struct_memberN;
};

The "struct" keyword indicates to the compiler that a structure has been declared.
The "structurename" defines the name of the structure. Since the structure declaration is treated
as a statement, so it is often ended by a semicolon.

What is Class in C++?

A class in C++ is similar to a C structure in that it consists of a list of data members and a set of
operations performed on the class. In other words, a class is the building block of Object-
Oriented programming. It is a user-defined object type with its own set of data members and
member functions that can be accessed and used by creating a class instance. A C++ class is
similar to an object's blueprint.

Syntax:

The structure and the class are syntactically similar. The syntax of class in C++ is as follows:

class class_name
{
// private data members and member functions.
Access specifier;
Data member;
Member functions (member list){ . . }
};

In this syntax, the class is a keyword to indicate the compiler that a class has been declared. OOP's
main function is data hiding, which is achieved by having three access specifiers: "public",
"private", and "safe". If no access specifier is specified in the class when declaring data
members or member functions, they are all considered private by default.

The public access specifier allows others to access program functions or data. A member of that
class may reach only the class's private members. During inheritance, the safe access specifier is
used. If the access specifier is declared, it cannot be changed again in the program.

Comparison between the structure and class

Here, we are going to discuss a head-to-head comparison between the structure and class. Some of
them are as follows:

Features Structure Class

Definition A structure is a grouping of In C++, a class is defined as a


variables of various data types collection of related variables and
referenced by the same name. functions contained within a single
structure.

Basic If no access specifier is specified, If no access specifier is defined, all


all members are set to 'public'. members are set to 'private'.

Declaration struct structure_name{ class class_name{


type struct_member 1; data member;
type struct_member 2; member function;
type struct_member 3; };
.
type struct_memberN;
};

Instance Structure instance is called the A class instance is called 'object'.


'structure variable'.

Inheritance It does not support inheritance. It supports inheritance.

Memory Memory is allocated on the stack. Memory is allocated on the heap.


Allocated

Nature Value Type Reference Type

Purpose Grouping of data Data abstraction and further


inheritance.

Usage It is used for smaller amounts of It is used for a huge amount of data.
data.

Null values Not possible It may have null values.

Requires It may have only parameterized It may have all the types of
constructor and constructor. constructors and destructors.
destructor

Similarities

The following are similarities between the structure and class:

o Both class and structure may declare any of their members private.
o Both class and structure support inheritance mechanisms.
o Both class and structure are syntactically identical in C++.
o A class's or structure's name may be used as a stand-alone type.

#include <iostream>
using namespace std;
struct st
{

void sum()
{
cout<<"new"<<endl;
}
};
class Demo
{
public:
void fun()
{
cout<<"welcome"<<endl;
}
};
int main()
{
Demo d;
st s;
d.fun();
s.sum();
}

Static Class Member

Static members exist as members of the class rather than as an instance in each object of the
class. So, this keyword is not available in a static member function. Such functions may access
only static data members. There is a single instance of each static data member for the entire
class, which should be initialized, usually in the source file that implements the class member
functions. Because the member is initialized outside the class definition, we must use fully
qualified name when we initialize it:

class_name::static_member_name = value;

#include <iostream>

using namespace std;

class Box
{
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
static int objectCount;
double sum=0;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{

cout <<"Constructor called." << endl;


length = l;
breadth = b;
height = h;
sum=length * breadth * height;
// Increase every time object is created
objectCount++;
}
void Volume()
{

cout<< sum<<"\n";
}
};

// Initialize static member of class Box


int Box::objectCount = 0;

int main()
{

Box Box1(3.3, 1.2, 1.5); // Declare box1


Box Box2(8.5, 6.0, 2.0); // Declare box2
Box1.Volume();
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;

return 0;
}

Output
Constructor called.
Constructor called.
5.94
Total objects: 2

const and Classes

The 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:
const Class_Name Object_name;

 When a function is declared as const, it can be called on any type of object, const object as
well as non-const objects.
 Whenever an object is declared as const, it needs to be initialized at the time of declaration.
however, the object initialization while declaring is possible only with the help of
constructors.
A function becomes const when the const keyword is used in the function’s declaration. The idea
of const functions is not to allow them to modify the object on which they are called. It is
recommended the practice to make as many functions const as possible so that accidental changes
to objects are avoided.

// Demonstration of constant object,


// show that constant object can only
// call const member function
#include <iostream>
using namespace std;

class Test
{
int value;

public:
Test(int v = 0)
{
value = v;
}

int getValue() const


{
return value;
}
};

int main()
{
const Test t(20);
cout << t.getValue();
return 0;
}

Output
20
Inline function in C++
If make a function as 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.

Normally, a function call transfers the control from the calling program to the called function.
This process of jumping to the function, saving registers, passing a value to the argument, and
returning the value to the calling function takes extra time and memory.

An inline function is a function that is expanded inline when it is invoked, thus saving time. The
compiler replaces the function call with the corresponding function code, which reduces the
overhead of function calls.

When an inline function is called, the compiler replaces all the calling statements with the
function definition at run-time. Every time an inline function is called, the compiler generates a
copy of the function’s code, in place, to avoid the function call.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code?
}

inline return-type function-name(parameters)


{
// function code
}

Example Program

#include <iostream>
using namespace std;

inline int max_num(int x, int y)


{
return (x > y)? x : y;
}

// Main function for the program


int main()
{
cout << "Greater of ( 40, 50 ) is: " << max_num(40,50) << endl;
cout << "Greater of ( 90, 50 ) is: " << max_num(90,50) << endl;
cout << "Greater of ( -5, 34 ) is: " << max_num(-5,34) << endl;
return 0;
}

Greater of ( 40, 50 ) is: 50


Greater of ( 90, 50 ) is: 90
Greater of ( -5, 34 ) is: 34

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

You might also like