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

cpp_unit_1

This document provides an introduction to Object-Oriented Programming (OOP) using C++, detailing its characteristics, merits, and demerits. It covers fundamental OOP concepts such as classes, objects, inheritance, polymorphism, data encapsulation, and abstraction, emphasizing the advantages of organizing data and functions together. The document also includes a brief history of C++ and examples of basic programming structures and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

cpp_unit_1

This document provides an introduction to Object-Oriented Programming (OOP) using C++, detailing its characteristics, merits, and demerits. It covers fundamental OOP concepts such as classes, objects, inheritance, polymorphism, data encapsulation, and abstraction, emphasizing the advantages of organizing data and functions together. The document also includes a brief history of C++ and examples of basic programming structures and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Unit 1

Object Oriented Programming


Using C++

Dr. Dheresh Soni


UNIT 1
Introduction to object-oriented approach
• Syllabus: Why object-oriented • default argument
programming • function-reference:
• Characteristics of object-oriented • independent reference –

language: • function returning reference


• pass by reference
• Basic concept of OOPs
• Merits of OOPs
• Demerits of OOPs.
• Inline function –
Why object-oriented programming
• The major motivating factor in the invention of object-oriented approach is to remove
some of the flaws encountered in the procedural approach.

• OOP treats data as a critical element in the program development and does not allow it to
flow freely around the system.

• It ties data more closely to the functions that operate on it, and protects it from accidental
modification from outside functions;

• OOP allows decomposition of a problem into a number of entities called objects and then
builds data and functions around these objects.

• The organization of data and functions in object-oriented programs is shown in Fig. 1.


The data of an object can be accessed only by the functions associated with that object.
However, functions of one object can access the functions of other objects.
Why object-oriented programming
•Object-oriented programming is not the
right of any particular language, like
structured programming, OOP
concepts can be implemented using
languages such as C++ and Pascal;

•However, programming becomes clumsy


and may generate confusion when the
programs grow large. A language that is
specially designed to support the OOP
concepts makes it easier to implement
them.
Why object-oriented programming
•The languages should support several of the OOP concepts to claim that they are object
oriented. Depending upon the features they support, they can be classified into the following
two categories;
1. Object-based programming languages, and
2. Object-oriented programming languages
•Object-based programming is the style of programming that primarily supports encapsulation
and object identity,

•Major features that are required for object-based programming are:


i. Data encapsulation
ii. Data hiding and access mechanisms
iii. Automatic initialization and clear-up Of Objects
iv. Operator overloading
Why object-oriented programming
•Languages that support programming with objects are said to be object-based
programming languages. They do not support inheritance and dynamic binding. ADA is
a typical object-based programming language.

•Object-oriented programming incorporates all of object-based programming features along


with two additional features, namely, inheritance and dynamic binding. Object-oriented
programming can therefore be characterized by the following statement:

•Object-based features + inheritance + dynamic binding

•Object-oriented programming is the most recent concept among programming paradigms


and still means different things to different people.

•We define oriented programming as an approach that provides a way of modularizing


programs by creating partitioned memory area for both data and functions that can be used
as templates for creating copies of modules.
Why object-oriented programming
•Introduction to C++
•C++ is object-oriented programming language. It was developed by Bjarne Stroustrup at
AT&T Bell Laboratories in Murray Hill, New Jersey, USA„ in the early 1980’s.

•Stroustrup and a strong supporter of C, wanted to combine of both the languages and create
a more powerful language that could support object-oriented programming features and still
retain the power and elegance of C.

•The result was C++. Therefore, C++ an extension of C with a major addition of the class,
constructs features. The idea of C++ comes from the C increment operator ++, thereby
suggesting that C++ is an incremented version of C.
Why object-oriented programming
•C++ is a superset of C. The most Simple Program
important facilities that C++ adds on
to C are classes, inheritance, #include<iostream.h>
function overloading, and operator #include<conio.h>
overloading.
void main()
•These features enable creating of {
abstract data types inherit properties int a, b, c;
from existing data types and support clrscr();
polymorphism, thereby making C++ a cout<< “enter the value a and b”;
truly object-oriented language. cin >> a>>b;
c=a+b;
cout<<”sum is: ”<< c;
getch();
}
Why object-oriented programming
•The object-oriented features in C++ allow programmers to build large programs with
clarity, extensibility and ease of maintenance, the spirit and efficiency of C.

•Program Explanation

• # is macro pre processor. Show the path to add header files.


• iostream .h, conio.h is header file. Full form iostream .h input output stream header file.
conio.h consol input output header file. To identify header file see extension .h
• void is key word use to avoid return type.
• main() is function. If small bracket () is followed by any name or string then it is function.
• { } body start with curly bracket.
• int is keyword. Hold value without decimal.
Why object-oriented programming
• clrscr() is function name clear the screen use for clearing the old output data of screen.
• cout<< is output string to show output on screen. Output content should be in “”.
• cin>> is input string use to take input from user.
• getch() is function use to hold the output screen to see result.

•Comments - C++ introduces a new comment symbol // (double slash). The double slash
comment is basically a single line comment.

•Example: // C++ program to illustrate

•Multiline comments can be written as follows:


•Example: /* This is an example of
C++ program to illustrate
some of its features */
Why object-oriented programming
•Output Operator - The only statement use for output.

cout<<”C++ is better than C”;

•This statement introduces two new C++ features cout and <<.

•The iostream File - We have used the following #include directive in the program
#include<iostream.h>.

•Namespace - Namespace is a new concept introduced by the ANSI C++ standards


committee. This defines a scope for the identifiers that are used in a program.

like using namespace std;

•This will bring all the identifiers defined in std to the current global scope. using and
namespace are the new keywords of C++.
Why object-oriented programming
•Return Type of main( ) - In C++ main() returns an integer type value to the operating
system.

return(0) statement; otherwise a warning or an error might occur.

•Variable – Variable are those whose value is not fix. The program uses any number of
variables. They can be declared as type of data type by the statement. All variables must be
declared before they are used in the program.

Example: float num;

•Input Operator - The statement cin>> number; is an input statement and causes the
program to wait for the user to type in a number.

cin >> a;
Why object-oriented programming
•Cascading of I/O Operators - The multiple
use of << or >> in one statement is called
cascading.

cout<<”Sum = ”<<sum<<”\n”;
cin>>a>>b”\n”;

•Program structure of C++ program

•One of the major features of C++ is classes.


They provide a method of binding together
data and functions which operate on them.
Like structures in C, classes are user-defined
data program shows the use of class in C++
program.
Why object-oriented programming
#include<iostream.h> cout<<””enter age”;
#include<conio.h> cin>>age;
class person }
{ void person::putdata(void)
char name[30]; {
int age; cout<<”name is:”<<name;
public: cout<<”age is:”<<age;
void getdata(void); }
void putdata(void); void main()
}; {
person p;
// function declared outside the class clrscr();
void person::getdata(void) p.getdata();
{ p.putdata();
cout<<”enter the name”; getch();
cin>>name; }
Why object-oriented programming
#include<iostream.h> void putdata(void)
#include<conio.h> {
class person cout<<”name is:”<<name;
{ cout<<”age is:”<<age;
char name[30]; }
int age; };
public:
void main()
// function declared intside the class {
void getdata(void) person p;
{ clrscr();
cout<<”enter the name”; p.getdata();
cin>>name; p.putdata();
cout<<””enter age”; getch();
cin>>age; }
}
Why object-oriented programming
•The program defines person as a new data of type class.

• The class person includes two basic data type items and
two functions to operate on that data.

•These functions are called member functions and data


are called data member.

•The main-program uses person to declare variables of its


type.

•As pointed out earlier, class variables are known as


objects. Here, p is an object of type person. Class objects
are used to invoke the functions defined in that class.
Why object-oriented programming
•It is a common practice to organize a program into three separate files.

•The class declarations are placed in a header file and the definitions of member functions go
into another file. This approach enables the programmer to separate the abstract
specification of the interface (class definition) from the implementation details (member
functions definition).

•Finally, the main program that uses the class is placed in a third file which “include” the
previous two files as well as any other files required.

•This approach is based on the concept of client-server model as shown in previous Fig. The
class definition including the member functions constitute the server that provides services to
the main program known as client, The client uses the server through the public interface of the
class.
Why object-oriented programming
•Procedure oriented programming •Object oriented programming (OOP)

1. Emphasis is on doing things 1. Emphasis is on data rather than procedure.


(algorithms). 2. Programs are divided into what are known
2. Large programs are divided into smaller as objects.
programs known as functions. 3. Data structures are designed such that they
3. Most of the functions share global data. characterize the objects.
4. Data move openly around the system 4. Data is hidden and cannot be accessed by
from function to function. external functions.
5. Functions transform data from one form 5. Functions that operate on the data of an
to another. object are tied together in the data structure.
6. Employs top-down approach in program 6. Follows bottom-up approach in program
design. design.
Why object-oriented programming
•Procedure oriented programming •Object oriented programming (OOP)
7. Objects are not available for 7. Objects may communicate with each
communication with each other. other through functions.
8. New data and functions can be easily 8. New data and functions can be easily
added on top of program before using it. added whenever necessary.
Characteristics of object-oriented language
1. Basic building blocks OOP and a single entity which has data and operations on data
together
2. The instances of a class which are used in real functionality – its variables and operations
3. Specifying what to do but not how to do ; a flexible feature for having a overall view of an
object’s functionality.
4. Binding data and operations of data together in a single unit – A class adhere this feature
5. Reusability and extension of existing classes
6. Multiple definitions for a single name - functions with same name with different
functionality; saves time in investing many function names Operator and Function
overloading
7. Class definitions for unspecified data. They are known as container classes. They are
flexible and reusable.
8. Built-in language specific classes
Characteristics of object-oriented language
9. Objects communicates through invoking methods and sending data to them. This feature of
sending and receiving information among objects through function parameters is known as
Message Passing.
Basic concept of OOPs
•It is necessary to understand of the concepts extensively in object-oriented programming.
These include:

1. Objects 5. Inheritance
2. Classes 6. Polymorphism
3. Data abstraction 7. Dynamic binding
4. Data encapsulation 8. Message passing

•Objects –
• Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program
has to handle.
• They may also represent user-defined data such as vectors, time and lists. Programming
problem is analyzed in terms of objects and the nature of communication between
them.
Basic concept of OOPs
• Program objects should be chosen such that they match closely
with the real-world objects. When a program is executed, the
objects interact by sending messages to one another.
• Each object contains data, and code to manipulate the data.
Objects can interact without having to know details of each
other's data or code. It is sufficient to know the type of message
accepted, and the type of response returned by the objects.

• For example - STUD STUDENT


Class object
•Classes –
• We know that objects contain data, and code to manipulate that
data. The entire set of data and code of an object can be made a
user-defined data type with the help of a class.
Basic concept of OOPs
• In fact, objects are variables of the type class. Once a class has been defined, we can
create any number of objects belonging that Class. Each object is associated with the data
of type class with which they are created. A class is thus a collection of objects of similar
type.

• For example - class fruits


fruits mango

• Classes are user-defined data types and behave like the built-in types of programming
language. fruit mango; will create an object mango belonging to the class fruit.

•Data Encapsulation –
• The wrapping up of data and functions into a single unit (called class} is known as
encapsulation. Data encapsulation is the most striking feature of a class.
Basic concept of OOPs
• The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between the
data and the program.
• This insulation of' the data from direct access by the program is called data hiding or
information hiding.

•Data Abstraction –
• Abstraction refers to the act of representing essential features without including the
background details or explanations.
• Classes use the concept of abstraction and are defined a list of abstract attributes Such as
Size, weight and cost, and functions to operate on these attributes.
• They encapsulate all the essential properties of the objects that are to be created. The
attributes are sometimes called data members because they hold information. The
functions that operate on these data are sometimes called method is or member
functions.
Basic concept of OOPs
• Since the Classes use the concept of data abstraction, they are known as Abstract Data
Types.

•Inheritance –
• Inheritance is the process by which objects of acquire the properties of objects of
another.
• In OOPs, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it.
• This is possible by deriving a new class from the existing one. The new class will have
the combined features of both the classes.
• The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduce any undesirable Side-effects into the rest
of the classes.
Basic concept of OOPs
• For example, the bird 'robin' is a part of the class 'flying bird' which is again a part of the
class "bird'. The principle behind this sort of division is that each derived Class shares
characteristics with the class from which it is derived as illustrated in Fig.
Basic concept of OOPs
•Polymorphism –
• Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
the ability to take more than one form.
• An operation may exhibit different behaviours in different instances. The behaviour
depends upon the types of data used in the operation.
• For example, consider the operation of addition. For two numbers, the operation will
generate a sum. If the operands are strings, then the operation would produce a third string
by concatenation. The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
• A single function name can be used to handle different number and different types of
arguments. This is something similar to a particular word having several different
meanings depending on the context. Using a single function name to perform d types of
tasks is known function overloading.
Basic concept of OOPs
• Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of
operations.

•Dynamic Binding –
• Binding refers to the linking of a procedure call to the code to be executed in response to
the call, Dynamic binding (also known as late binding) means that the associated with a
given procedure call is not known until the time of the call at run-time.
Basic concept of OOPs
• It is associated with polymorphism and inheritance. A function associated with a
polymorphic reference depends on the dynamic type of that reference.
• Consider the procedure "draw" in above Fig. By inheritance, every object will have this
algorithm is, however, unique to each object and so the draw procedure will be redefined
in each class that defines the object. At run-time the code matching the object under
current reference will be called.

•Message Passing –
• An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, therefore, involves the
following basic steps:

1. Creating Classes that define objects and their behaviour.


2. Creating objects from class definitions, and
Basic concept of OOPs
3. Establishing communication among objects.

• Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
• A message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure} in the receiving object that generates the desired result.
• Message passing involves the name of the object, the name of the function (message)
and the information to be sent. Objects have a life cycle. They can be created and
destroyed. Communication with an object is feasible as long as it is alive. Example:

employee . salary (name);


Object message information
Merits of OOPs
1. Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
2. We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch.
3. The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by rode in other parts of the program.
4. It is possible to have multiple instances of an object to co-exist without any interference.
5. It is possible to map objects in the problem domain to those in the program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more details of a model in
implementable form.
8. Object-oriented systems can be easily upgraded from small to large systems.
Merits of OOPs
9. Message passing techniques for communication between objects makes the interface
descriptions with external systems much simpler.
10. Software complexity can be easily managed.
Demerits of OOPs
1. The length of the programmes developed using OOP language is much larger than the
procedural approach.
2. Since the programme becomes larger in size, it requires more time to be executed that
leads to slower execution of the programme.
3. We can not apply OOP everywhere as it is not a universal language. It is applied only
when it is required. It is not suitable for all types of problems.
4. Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
5. OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
6. Everything is treated as object in OOP so before applying it we need to have excellent
thinking in terms of objects.
Application of OOPs
•The promising areas for application of OOP include:
a. Real-time systems
b. Simulation and modeling
c. Object-oriented databases
d. Hypertext, hypermedia and expertext
e. A1 and expert systems
f. Neural networks and parallel programming
g. Decision support and office automation systems
h. CAM/CAD
Inline function
•Function –
• A function is a set of statements that takes input, does some specific computation, and
produces output. The idea is to avoiding the writing the same code again and again for
different inputs, we can call this function.
• In simple terms, a function is a block of code that runs only when it is called.
return type parameter 1 , 2
Syntax: Int getdata (int x, Int y) ;
function name termination of statement
•Why Do We Need Functions?
1. Functions help us in reducing code redundancy.
2. Functions make code modular.
3. Functions provide abstraction.
Inline function
•A C++ function consist of two parts:

1. Declaration: A function declaration tells the compiler about the number, data types of
parameters, and returns type of function. Writing parameter names in the function
declaration is optional but it is necessary to put them in the definition.
2. Definition: A function definition talks about the body of the function (code to be
executed)

Syntax
void myFunction() // declaration
{
// the body of the function (definition)
}
Inline function
•Types of Functions
1. User Defined Function - Defined by user/customer.-Defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly known
as “tailor-made functions” .
2. Library or Pre-defined Function - Library functions are also called “built-in
Functions“. These functions are part of a compiler package that is already defined and
consists of a special function with special and different meanings. Built-in Function
gives us an edge as we can directly use them without defining them whereas in the
user-defined function we have to declare and define a function before using them. For
Example: sqrt(), setw(), strcat(), etc.

•Inline function –
• One of the objectives of using functions in a program is to save some memory space,
which becomes appreciable when a function is likely to be called many times.
Inline function
• However, every time a function is called, it takes lot of extra time in executing a of
instructions.
• When a function is small, n substantial percentage of execution time may be spent in
overheads.
• One solution to this problem is to use macro definitions, popularly known as macros.
Preprocessor macros are popular in C.
• The major drawback with macros is that they are not really functions and therefore the
usual error checking does not occur during compilation. #define abc 23

• C++ has a different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called inline function.
• An inline function is a function that is expanded in line when it is invoked, That is, the
compiler replaces the function call with the corresponding function code (something
similar to macros expansion).
• The inline functions defined as follows:
Inline function
Syntax
inline function-header
{ function body }

Example
inline double_cube(double a)
{ return (a*a*a); }

•Features of Inline function

• This makes the inline feature far superior to macros.


• It is easy to make a function inline.
• All we need to do is to prefix the keyword inline to the function definition.
• All inline functions must be defined before they are called.
Inline function
• We should exercise care before making a function inline. The speed benefits of inline
functions diminish as the function grows in size.
• At some point the overhead of the function call becomes small compared to the
execution of the function, and the benefits of inline functions may be lost. In such cases
the use of normal functions will be more meaningful.

•Some of the situations where inline expansion may not work are:

1. For functions returning values. if a loop, a switch, or a goto exists.


2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4. If inline function are recursive.

Example - in next slide


Inline function
#include<iostream.h>
#include<conio.h>

inline float mul(float x, float y)


{ return (x*y); }

int main( )
{
clrscr();
float a=2.5;
float b=3.5;
cout<<"Multiplication is :"<<mul(a, b);
return 0;
}
Default argument function
▪ When we define function and at the time of function declaration, the variable declare in
function brackets are known as parameter.
▪ 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.

▪ Characteristics for defining the default arguments

1. The values passed in the default arguments are not constant. These values can be
overwritten if the value is passed to the function. If not, the previously declared value
retains.
2. During the calling of function, the values are copied from left to right.
3. All the values that will be given default value will be on the right.
▪ The following is a simple C++ example to demonstrate the use of default arguments.
Default argument function
Example

#include <iostream.h>
#include <conio.h>

int sum(int x, int y, int z = 0, int w = 0) //assigning default values


{
return (x + y + z + w);
}

void main()
{
cout << sum(10, 15) << endl; // Statement 1
cout << sum(10, 15, 25) << endl; // Statement 2
cout << sum(10, 15, 25, 30) << endl; // Statement 3
}
Reference: Independent reference
•C++ supports two types of variables:

1. An ordinary variable is a variable that contains the value of some type.


2. A pointer is a variable that stores the address of another variable.

•There is another variable that C++ supports, i.e., references variable.

•Reference

• Reference is a variable that behaves as an alias for another variable. Reference can be
created by simply using an ampersand (&) operator.

• When we create a variable, then it occupies some memory location. We can create a
reference of the variable; therefore, we can access the original variable by using either
name of the variable or reference.
Reference: Independent reference
• For example, int a=10;
• Now, we create the reference variable of the above variable. int &ref=a;

•C++ provides two types of references:


1. References to non-const values
2. References as aliases

2. References to non-const values - It can be declared by using & operator with the
reference type variable.
Example
#include <iostream.h>
int main()
{
int a=10;
int &value=a;
Reference: Independent reference
cout << value << endl;
return 0;
}
2.References as aliases - References as aliases is another name of the variable which is being
referenced.
For example,
#include <iostream.h>
int main()
{ a=10 -110111
int a=10; // variable initialization &b=a 110111
int &b=a; b=a 10
int &c=a;
cout << "Value of a is :" <<a<<endl;
cout << "Value of b is :" <<b<<endl;
cout << "Value of c is :" <<c<< endl;
Reference: Independent reference
return 0;
}

•Properties of References - The following are the properties of references:

1. Initializátion - It must be initialized at the time of the declaration.


2. Reassignment - It cannot be reassigned means that the reference variable cannot be
modified.

•Differences between Reference and Pointer

1. Definition - A reference variable is another name for an already existing variable. It


is mainly used in 'pass by reference' where the reference variable is passed as a
parameter to the function and the function to which this variable is passed works on the
original copy of the variable.
Reference: Independent reference
int a = 10;
int &p = a; Reference

int a = 10; or int *p, a=10;


int *p = &a; *p = &a; pointer

2. Declaration - We can declare a reference variable by adding a '&' symbol before a


variable. While we declare a pointer variable, and this variable is created by adding a
'*' operator before a variable.

3. Reassignment - We cannot reassign the reference variable. Multiple declarations


of int &a are not allowed. Whereas, the pointers can be re-assigned and it is useful
when we are working with the data structures such as linked list, trees, etc.
Reference: Independent reference
Reference reassignment Not allowed Pointer reassignment allowed

int a = 5; int a = 5;
int b = 6; int b = 6;
int *p;
int &p = a; *p = &a;
Int &p = b; *p = &b;

4. Memory Address - In the case of reference, both the reference and actual variable
refer to the same address. The new variable will not be assigned to the reference
variable until the actual variable is either deleted or goes out of the scope.

int a = 5;
int b = 6;
int &p = a;
Reference: Independent reference
int &p = b; // Throw an error of "multiple declaration of reference"
int &q = b; // However it is valid statement,

int *p
&p = a; // pointer address
cout << &p << endl << &a;

5. NULL value - We cannot assign the NULL value to the reference variable, but the
pointer variable can be assigned with a NULL value.

6. Indirection – Pointers can have pointer to pointer offering more than one level of
indirection but reference of reference is not allowed

int a = 10;
int *p;
int **q; // It is valid.
p = &a;
Reference: Independent reference
q = &p;

int &p = a;
int &&q = p; // It is reference to reference, so it is an error

7. Arithmetic Operations - As we know that arithmetic operations can be applied to the


pointers named as "Pointer Arithmetic", but arithmetic operations cannot be applied
on the references. There is no word, i.e., Reference Arithmetic exists in C++.
Pass by reference
•The most popular ways to pass parameters are as follows:

1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are stored in
different memory locations so any changes made in the functions are not reflected in the
actual parameters of the caller.

Example - // C++ Program to demonstrate function definition

#include <iostream>

void fun(int x) // formal parameter


{
x = 30; // definition of function
}
Pass by reference
int main()
{
int x = 20;
fun(x); // actual parameter
cout << "x = " << x;
return 0;
}

2. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are reflected in the actual parameters of the caller.

Example
#include <iostream.h>

void func(int &); //function prototyping


Pass by reference
int main()
{
int a=10;
cout <<"Value of 'a' is :" <<a<<endl;
func(a);
cout << "Now value of 'a' is :" <<a<< endl;
return 0;
}

void func(int &m)


{
m=8;
}

2. Functions Using Pointers - The third way to use functions with pointer.
Pass by reference
• The function fun() expects a pointer ptr to an integer (or an address of an integer). It
modifies the value at the address ptr. The dereference operator * is used to access the
value at an address.
• In the statement ‘*ptr = 30’, the value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function
call statement ‘fun(&x)’, the address of x is passed so that x can be modified using its
address.

// C++ Program to demonstrate working of function using pointers

#include <iostream>

void fun(int* ptr)


{
*ptr = 30;
}
Pass by reference
int main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}

You might also like