Object-Oriented Programming (OOP) : Dr. G. Prabu Kanna Associate Professor / Ce

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 82

Object-oriented programming (OOP)

Dr. G. PRABU KANNA


ASSOCIATE PROFESSOR / CE
Object-oriented programming (OOP)

• Object-oriented programming (OOP) is a programming paradigm based on


the concept of "objects", which may contain data, in the form of fields,
often known as attributes; and code, in the form of procedures, often
known as methods.

• For example, a person is an object which has certain properties such as


height, gender, age, etc. It also has certain methods such as move, talk,
and so on.
Object-oriented programming (OOP)
Object-oriented programming (OOP)

Object
• This is the basic unit of object-oriented programming.
That is both data and function that operate on data are
bundled as a unit called an object.

Class
• When you define a class, you define a blueprint for an
object. This doesn't actually define any data, but it does
define what the class name means, that is, what an object
of the class will consist of and what operations can be
performed on such an object.
Object-oriented programming (OOP)

OOP has four basic concepts on which it is totally based.

• Abstraction

• Encapsulation

• Inheritance

• Polymorphism
Object-oriented programming (OOP)

OOP has four basic concepts on which it is totally based.

• Abstraction

• It refers to, providing only essential information to the outside world and
hiding their background details.

• For example, a web server hides how it processes data it receives, the end
user just hits the endpoints and gets the data back.
Object-oriented programming (OOP)

OOP has four basic concepts on which it is totally based.

Encapsulation

• Encapsulation is a process of binding data members (variables, properties)


and member functions (methods) into a single unit.

• It is also a way of restricting access to certain properties or component.


The best example for encapsulation is a class.
Object-oriented programming (OOP)
OOP has four basic concepts on which it is totally based.

Inheritance

The ability to create a new class from an existing class is called


Inheritance.
Using inheritance, we can create a Child class from a Parent class such
that it inherits the properties and methods of the parent class and can have its
own additional properties and methods.

For example,
if we have a class Vehicle that has properties like Color, Price, etc,
we can create 2 classes like Bike and Car from it that have those 2
properties and additional properties that are specialized for them like a car has
number of Windows while a bike cannot.
Same is applicable to methods.
Object-oriented programming (OOP)
OOP has four basic concepts on which it is totally based.

Polymorphism

The word polymorphism means having many forms. Typically, polymorphism


occurs when there is a hierarchy of classes and they are related by
inheritance.

C++ polymorphism means that a call to a member function will cause a


different function to be executed depending on the type of object that
invokes the function.
Advantage of OOPs over Procedure-oriented programming language

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

• OOPs provide data hiding whereas in Procedure-oriented programming


language a global data can be accessed from anywhere.

• 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.
Procedural Vs. Object Oriented Programmin

Procedural Oriented Programming Object Oriented Programming


In procedural programming, program is In object oriented programming, program
divided into small parts called functions. is divided into small parts called objects.
Procedural programming follows top down Object oriented programming follows
approach. bottom up approach.
There is no access specifier in procedural Object oriented programming have access
programming. specifiers like private, public, protected
etc.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have Object oriented programming provides
any proper way for hiding data so it is less data hiding so it is more secure.
secure.
Procedural Vs. Object Oriented Programmin

Procedural Oriented Programming Object Oriented Programming


In procedural programming, overloading is Overloading is possible in object oriented
not possible. programming.
In procedural programming, function is In object oriented programming, data is
more important than data. more important than function.
Procedural programming is based on Object oriented programming is based on
unreal world. real world.
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
Procedural Vs. Object Oriented Programming

Both Procedural Oriented Programming (POP) and Object Oriented


Programming (OOP) are the high level languages in programming world and
are widely used in development of applications.

On the basis of nature of developing the code both languages have different
approaches on basis of which both are differentiate from each other.
Benefits of OOP
It is easy to model a real system as real objects are represented by
programming objects in OOP. The objects are processed by their member
data and functions. It is easy to analyze the user requirements.

With the help of inheritance, we can reuse the existing class to derive a new
class such that the redundant code is eliminated and the use of existing class
is extended. This saves time and cost of program.

In OOP, data can be made private to a class such that only member functions
of the class can access the data. This principle of data hiding helps the
programmer to build a secure program that can not be invaded by code in
other part of the program.
Benefits of OOP

With the help of polymorphism, the same function or same operator can be
used for different purposes. This helps to manage software complexity easily.

Large problems can be reduced to smaller and more manageable problems. It


is easy to partition the work in a project based on objects.

It is possible to have multiple instances of an object to co-exist without any


interference i.e. each object has its own separate member data and function.
Applications of Object Oriented Programming

Main application areas of OOP are:

• User interface design such as windows, menu.


• Real Time Systems
• Simulation and Modeling
• Object oriented databases
• AI and Expert System
• Neural Networks and parallel programming
• Decision support and office automation systems etc.
C++ Features
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();

}
To write the first C++ program, open the C++ console
and write the following code:
#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.
How to compile and run the C++ program

There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++
program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.
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.
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;
int d=3, f=5;
byte z=22;
char x=’x’;

Invalid variable names:

int 4;
int x y;
int double;
C++ Data Types
• A data type specifies the type of data that a variable can store such as
integer, floating, character etc.
C++ Data Types
• There are 4 types of data types in C++ language.

Types Data Types


Basic Data Type int, char, float, double, etc
Derived Data Type array, pointer, etc
Enumeration Data Type enum
User Defined Data Type structure
Basic Data Types

• The basic data types are integer-based and floating-point based. C++
language supports both signed and unsigned literals.

• The memory size of basic data types may change according to 32 or 64 bit
operating system.

• Let's see the basic data types. It size is given according to 32 bit OS.
Basic Data Types

Data Types Memory Size Range


char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
Namespaces in C++

• Consider a situation, when we have two persons with the same name,
Zara, in the same class.

• Whenever we need to differentiate them definitely we would have to


use some additional information along with their name, like either the
area, if they live in different area or their mother’s or father’s name,
etc.

• Same situation can arise in your C++ applications. For example, you
might be writing some code that has a function called xyz() and there
is another library available which is also having same function xyz().

• Now the compiler has no way of knowing which version of xyz()


function you are referring to within your code.
Namespaces in C++

• A namespace is designed to overcome this difficulty and is used as


additional information to differentiate similar functions, classes, variables
etc. with the same name available in different libraries.

• Using namespace, you can define the context in which names are defined.
In essence, a namespace defines a scope
Namespaces in C++
• #include <iostream>
• using namespace std;

• // first name space


• namespace first_space {
• void func() {
• cout << "Inside first_space" << endl;
• }
• }

• // second name space


• namespace second_space {
• void func() {
• cout << "Inside second_space" << endl;
• }
• }

• int main () {
• // Calls function from first name space.
• first_space::func();

• // Calls function from second name space.
• second_space::func();

• return 0;
• }
• If we compile and run above code, this would produce the following result −

• Inside first_space
• Inside second_space
Namespaces in C++
The using directive

• You can also avoid prepending of namespaces with the using namespace
directive.

• This directive tells the compiler that the subsequent code is making use of
names in the specified namespace. The namespace is thus implied for the
following code −
Namespaces in C++
#include <iostream>
using namespace std;

// first name space


namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}

// second name space


namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}

using namespace first_space;


int main () {
// This calls function from first name space.
func();

return 0;
}

If we compile and run above code, this would produce the following result −

Inside first_space
Identifiers in C++

The C++ identifier is a name used to identify a variable, function, class,


module, or any other user-defined item. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters, underscores,
and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within


identifiers. C++ is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers −

mohit piyush def Any_name a_123

myname50 _temp j a23b9 retVal


Constants in C++
• As the name suggests the name constants are given to such variables or
values in C/C++ programming language which cannot be modified once they
are defined.

• They are fixed values in a program. There can be any types of constants like
integer, float, octal, hexadecimal, character constants, etc.

• Every constant has some range. The integers that are too big to fit into an int
will be taken as long.

• Now there are various ranges that differ from unsigned to signed bits.

• Under the signed bit, the range of an int varies from -128 to +127, and under
the unsigned bit, int varies from 0 to 255.
Constants in C++
Constants in C++
• Defining Constants:
• In C++ program we can define constants in two ways as shown below:

• Using #define preprocessor directive // #define NEWLINE ‘\n’


• Using a const keyword

• Literals: The values assigned to each constant variables are referred to as the
literals.

• Generally, both terms, constants and literals are used interchangeably.

• For eg, “const int = 5;“, is a constant expression and the value 5 is referred to as
constant integer literal.
• interger literals
• floating point literals
• boolean literals
• character literals
• String literals
Constants in C++
• Let us now learn about above two ways in details:

• Using #define preprocessor directive: This directive is used to declare


an alias name for existing variable or any value. We can use this to
declare a constant as shown below:

• #define identifierName value


• identifierName: It is the name given to constant.

• value: This refers to any value assigned to identifierName.

• using a const keyword: Using const keyword to define constants is as


simple as defining variables, the difference is you will have to precede
the definition with a const keyword
Constants in C++
C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH,
EAST and WEST) etc. The C++ enum constants are static and final implicitly.

C++ Enums can be thought of as classes that have fixed set of constants.
C++ Enumeration
Points to remember for C++ Enum
• enum improves type safety

• enum can be easily used in switch

• enum can be traversed

• enum can have fields, constructors and methods

• enum may implement many interfaces but cannot extend any class
because it internally extends Enum class
C++ Enumeration
C++ Enumeration Example
• #include <iostream>
• using namespace std;
• enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
• int main()
• {
• week day;
• day = Friday;
• cout << "Day: " << day+1<<endl;
• return 0;
• }

Output:

• Day: 5
C++ Enumeration
C++ Enumeration Example
• #include <iostream>
• using namespace std;
• enum colors{red=5, black};
• enum suit{heart, diamond=8, spade=3, club};
• int main() {
• cout <<"The value of enum color : "<<red<<","<<black;
• cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
• return 0;
• }

Output:

• The value of enum color : 5,6


• The default value of enum suit : 0,8,3,4
C++ Operators

Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.

Operators in C++ can be classified into 6 types:

Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
C++ Operators

Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.

Operators in C++ can be classified into 6 types:

Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
C++ Operators

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


Output
cout << "a - b = " << (a - b) << endl;

// printing the product of a and b a+b=9


cout << "a * b = " << (a * b) << endl;
a-b=5
// printing the division of a by b a * b = 14
cout << "a / b = " << (a / b) << endl;
a/b=3
// printing the modulo of a by b a%b=1
cout << "a % b = " << (a % b) << endl;

return 0;
}
Example 1: Arithmetic Operators

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
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; Output
cout << "\nAfter a += b;" << endl;
a=2
// assigning the sum of a and b to a b=7
a += b; // a = a +b
cout << "a = " << a << endl; After a += b;
a=9
return 0;}
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;
Output
result = a < b; // true
cout << "3 < 5 is " << result << endl;
3 == 5 is 0
result = a >= b; // false 3 != 5 is 1
cout << "3 >= 5 is " << result << endl; 3 > 5 is 0
result = a <= b; // true
3 < 5 is 1
cout << "3 <= 5 is " << result << endl; 3 >= 5 is 0
3 <= 5 is 1
return 0;
}
4. C++ Logical Operators
Operator Example Meaning
&& expression1 && Logical AND.
expression2 True only if all the
operands are true.

|| expression1 || expression2 Logical OR.


True if at least one of the
operands is true.
! !expression Logical NOT.
True only if the operand is
false.
c++ typecasting
• A type cast is basically a conversion from one type to another. There are two
types of type conversion:

1. Implicit Type Conversion Also known as ‘automatic type conversion’.


• Done by the compiler on its own, without any external trigger from the user.

Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.

All the data types of the variables are upgraded to the data type of the variable
with largest data type.
• bool -> char -> short int -> int ->

• unsigned int -> long -> unsigned ->

• long long -> float -> double -> long double


Example of Type Implicit Conversion:
• #include <iostream>
• using namespace std;

• int main()
• {
• int x = 10; // integer x
• char y = 'a'; // character c

• // y implicitly converted to int. ASCII


• // value of 'a' is 97
• x = x + y;

• // x is implicitly converted to float


• float z = x + 1.0;

• cout << "x = " << x << endl


• << "y = " << y << endl
• << "z = " << z << endl;
Output:
• return 0;
x = 107
• } y=a
z = 108
Explicit Type Conversion

2. Explicit Type Conversion:

This process is also called type casting and it is user-defined. Here the user
can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:

Converting by assignment: This is done by explicitly defining the required type


in front of the expression in parenthesis. This can be also considered as
forceful casting.
Example of Explicit Type Conversion
#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

Output:
Sum = 2
C++ Overloading (Function and Operator)

If we create two or more members having the same name but different in
number or type of parameter, it is known as C++ overloading. In C++, we can
overload:

• methods,
• constructors, and
• indexed properties

It is because these members have parameters only.


C++ Overloading (Function and Operator)

Types of overloading in C++ are:


• Function overloading
• Operator overloading
C++ Function Overloading

• Function Overloading is defined as the process of having two or more


function with the same name, but different in parameters is known as
function overloading in C++.

• In function overloading, the function is redefined by using either different


types of arguments or a different number of arguments.

• It is only through these differences compiler can differentiate between


the functions.

• The advantage of Function overloading is that it increases the readability


of the program because you don't need to use different names for the
same action.
C++ Function Overloading Example

• #include <iostream>
• using namespace std;
• class Cal {
• public:
• static int add(int a,int b){
• return a + b;
• }
• static int add(int a, int b, int c)
• {
• return a + b + c;
• }
• };
• int main(void) {
• Cal C; // class object declaration.
• cout<<C.add(10, 20)<<endl;
• cout<<C.add(12, 20, 23); Output:
• return 0;
• }
30
55
Program of function overloading with different types of
arguments.

• #include<iostream>
• using namespace std;
• int mul(int,int);
• float mul(float,int);


• int mul(int a,int b)
• {
• return a*b;
• }
• float mul(double x, int y)
• {
• return x*y;
• }
• int main()
• {
• int r1 = mul(6,7);
• float r2 = mul(0.2,3);
• std::cout << "r1 is : " <<r1<< std::endl;
• std::cout <<"r2 is : " <<r2<< std::endl; Output:
• return 0;
• }
r1 is : 42
r2 is : 0.6
Default arguments in C++
• #include <iostream>
• using namespace std;
• int sum(int a, int b=10, int c=20);

• int main(){
• /* In this case a value is passed as 1 and b and c values are taken from default arguments.*/
• cout<<sum(1)<<endl;

• /* In this case a value is passed as 1 and b value as 2, value of c values is taken from default arguments.
*/
• cout<<sum(1, 2)<<endl;

• /* In this case all the three values are passed during function call, hence no default arguments have been
used. */
• cout<<sum(1, 2, 3)<<endl;
• return 0;
• }
• int sum(int a, int b, int c){
• int z; Output:
• z = a+b+c;
• return z;
31
• }
23
6
Return by reference in C++

• // C++ program to illustrate return by reference • // Driver Code


• #include <iostream> • int main()
• using namespace std; • {
• // function to return as return by reference • int a = 20;
• int& returnValue(int& x) • int& b = returnValue(a);
• { •
• • cout << "a = " << a
• cout << "x = " << x • << " The address of a is "
• << " The address of x is " • << &a << endl;
• << &x << endl; •
• • cout << "b = " << b
• return x; • << " The address of b is "
• } • << &b << endl;
• •
• returnValue(a) = 13;
• cout << "a = " << a
• << " The address of a is "
• << &a << endl;
• return 0;
• }
Return by reference in C++
Output:
• x = 20 The address of x is 0x7fff3025711c
• a = 20 The address of a is 0x7fff3025711c
• b = 20 The address of b is 0x7fff3025711c
• x = 20 The address of x is 0x7fff3025711c
• a = 13 The address of a is 0x7fff3025711c
Control Structures
• A program is usually not limited to a linear sequence of instructions.

• During its process it may bifurcate, repeat code or take decisions.

• For that purpose, C++ provides control structures that serve to specify what
has to be done by our program, when and under which circumstances.

• With the introduction of control structures we are going to have to


introduce a new concept: the compound-statement or block.
Control Structures

• A block is a group of statements which are separated by semicolons (;) like


all C++ statements, but grouped together in a block enclosed in braces: { }:

• { statement1; statement2; statement3; }


Conditional structure: if and else

• The if keyword is used to execute a statement or block only if a condition is


fulfilled. Its form is:

• if (condition) statement

• Where condition is the expression that is being evaluated. If this condition is


true, statement is executed. If it is false, statement is ignored (not executed)
and the program continues right after this conditional structure.

if (x == 100)
cout << "x is 100";
Conditional structure: if and else

• If we want more than a single statement to be executed in case that the


condition is true we can specify a block using braces { }:

• if (x == 100)
• {
• cout << "x is ";
• cout << x;
• }
Conditional structure: if and else

• We can additionally specify what we want to happen if the condition is not


fulfilled by using the keyword else

• if (condition) statement1 else statement2

For example:
• if (x == 100)
• cout << "x is 100";
• else
• cout << "x is not 100";
Conditional structure: if and else

• The if + else structures can be concatenated with the intention of verifying a


range of values.

• The following example shows its use telling if the value currently stored in x
is positive, negative or none of them (i.e. zero):

• if (x > 0)
• cout << "x is positive";
• else if (x < 0)
• cout << "x is negative";
• else
• cout << "x is 0";
Iteration structures (loops)

• Loops have as purpose to repeat a statement a certain number of times or


while a condition is fulfilled.

• The while loop Its format is: while (expression) statement and its
functionality is simply to repeat statement while the condition set in
expression is true.
Iteration structures (loops)

For example, we are going to make a program to countdown using a while-loop:

• // custom countdown using while


• #include <iostream>
• using namespace std;
• int main ()
• {
• int n;
• cout << "Enter the starting number > ";
• cin >> n;

• while (n>0) {
• cout << n << ", ";
• --n; output:
• } Enter the starting number > 8
• cout << "FIRE!\n"; 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
• return 0;
Iteration structures (loops)
The do-while loop
• // number echoer
• #include <iostream>
• using namespace std;
• int main ()
• {
• unsigned long n;
• do {
• cout << "Enter number (0 to end): ";
• cin >> n;
• cout << "You entered: " << n<< "\n";
• } while (n != 0);
• return 0;
Output:
• } Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
The for loop

• Its format is:

• for (initialization; condition; increase) statement; and its main function is to


repeat statement while condition remains true, like the while loop.

• But in addition, the for loop provides specific locations to contain an


initialization statement and an increase statement. So this loop is specially
designed to perform a repetitive action with a counter which is initialized
and increased on each iteration.
The for loop

• // countdown using a for loop


• #include <iostream>
• using namespace std;
• int main ()
• {
• for (int n=10; n>0; n--) {
• cout << n << ", ";
• }
• cout << "FIRE!\n";
• return 0;
• }
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
FIRE!
Jump statements.
The goto statement
• goto allows to make an absolute jump to another point in the program.

• You should use this feature with caution since its execution causes an unconditional
jump ignoring any type of nesting limitations. The destination point is identified by a
label, which is then used as an argument for the goto statement. A label is made of a
valid identifier followed by a colon (:).
• // goto loop example
• #include <iostream>
• using namespace std;
• int main ()
• {
• int n=10;
• loop:
• cout << n << ", ";
• n--;
• if (n>0) goto loop; Output:
• cout << "FIRE!\n"; 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
• return 0; FIRE!
Jump statements.
The exit function
• exit is a function defined in the cstdlib library. The purpose of exit is to terminate the
current program with a specific exit code. Its prototype is:

– void exit (int exitcode);

• The exitcode is used by some operating systems and may be used by calling
programs. By convention, an exit code of 0 means that the program finished
normally and any other value means that some error or unexpected results
happened.
Jump statements.
The selective structure: switch
• The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression

• switch (x) {
• case 1:
• cout << "x is 1";
• break;
• case 2:
• cout << "x is 2";
• break;
• default:
• cout << "value of x unknown";
• }
Return by Reference
• In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference.

• #include <iostream>
• using namespace std;

• // Global variable
• int num;

• // Function declaration
• int& test();

• int main()
• {
• test() = 5;

• cout << num;


Output
• return 0;
• }
5
• int& test()
• {
• return num;
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.

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().
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);
• 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.
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;
• Output:
cout<<"Value of y is: "<<y<<endl;
• return 0; 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 Actual and formal arguments will be
created in different memory location created in same memory location

You might also like