0% found this document useful (0 votes)
0 views19 pages

Unit 1

The document provides an introduction to object-oriented programming (OOP), discussing its characteristics, advantages, and key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It highlights the differences between procedural and object-oriented programming, emphasizing the importance of data and modularity in OOP. Additionally, it introduces C++ as an object-oriented language, detailing its features and structure through examples and explanations of basic programming concepts.

Uploaded by

mkullu483
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views19 pages

Unit 1

The document provides an introduction to object-oriented programming (OOP), discussing its characteristics, advantages, and key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It highlights the differences between procedural and object-oriented programming, emphasizing the importance of data and modularity in OOP. Additionally, it introduces C++ as an object-oriented language, detailing its features and structure through examples and explanations of basic programming concepts.

Uploaded by

mkullu483
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT 1

Introduction to object-oriented approach


Syllabus: Introduction to object-oriented approach: Why object-oriented
programming- Characteristics of object-oriented language: classes and
objects encapsulation-data abstraction- inheritance - polymorphism - Merits
and Demerits of object oriented programming. Inline function – default
argument function-reference: independent reference – function returning
reference – pass by reference

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.

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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 1


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

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.

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.

In November 1907, the ANSI/ISO standards committee standardized these


changes and added several new features to the language specifications. C++
is a superset of C. The most important facilities that C++ adds on to C are
classes, inheritance, function overloading, and operator overloading.
These features enable creating of abstract data types, inherit properties
from existing data types and support polymorphism, thereby making C++ a
truly object-oriented language. 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.

Simple Program

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 2


#include<iostream.h>
#include<conio.h>
v oid main()
{
int a, b,c;
clrscr();
cout<< “enter the value a and b”;
cin >> a>>b;
c=a+b;
cout<<”sum is;”<< c; getch();
}

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


Comments start with a double Slash symbol and terminate at the end of the
line. A comment may start anywhere the line, and whatever follows till the
end of the line is ignored. Note that there is no closing symbol.

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 */

We can use either or both styles in our programs.

Output Operator - The only statement use for output.

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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 3


causes the string in quotation marks to be displayed on the screen. This
statement introduces two new C++ features cout and <<. The identifier cout
(pronounced as ”C out” is a predefined object that represents the standard
output stream in C++.

The iostream File - We have used the following #include directive in the
program #include<iostream.h>. This directive is the preprocessor to add
the contents of the iostream.h file to the program. It contains declarations
for the identifier cout and the operator <<. The header file iostream should
be included at the beginning of all programs that use input/output
statements.

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, For using the identifiers defined in the namespace
scope we must include the using directive, like using namespace std;
Here, std is the namespace where ANSI C++ standard class libraries are
defined. All ANSI C++ programs must include this directive. This will bring
all the identifiers defined in std to the current global scope. using and
namespace are the new keywords of C++.

Return Type of main( ) - In C++ main() returns an integer type value to


the operating system. Therefore, every main( ) in C++ should end with
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. The
number keyed in is placed in the variable number. The identifier cin
(pronounced 'C in) is a predefined object in corresponds to the standard
input stream. The operator >> is known as extraction or get from
operator, It extracts (or takes) the value from the keyboard and assigns it
to the variable on its right.

Cascading of I/O Operators - The statement cout<<”Sum =


”<<sum<<”\n”; first sends the string "Sum =" to cout and then sends the
value of sum. Finally, it sends the new line character that the next output
will be in the new line. The multiple use of << in one statement is called
cascading. When cascading an output operator, we should ensure
necessary blank spaces between different items.

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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 4


in C, classes are user-defined data program shows the use of class in C++
program.

#include<iostream.h>
#include<conio.h>
class person
{
char name[30];
int age;
public:
void getdata(void);
void putdata(void);
};

// function declared outside the class

void person::getdata(void)
{
cout<<”enter the name”;
cin>>name;
cout<<””enter age”;
cin>>age;
}

void person::putdata(void)
{
cout<<”name
is:”<<name;
cout<<”age is:”<<age;
}

void main()
{
person p;
clrscr();
p.getdata();
p.putdata();
getch();
}

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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 5


objects. Here, p is an object of type person. Class objects are used to invoke
the functions defined in that class.

As it can be seen from the above program, a typical C++ program would
contain four sections as shown in program. These sections may be placed in
separate code files and then compiled independently or jointly.

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


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.

Procedure oriented programming vs. object oriented


programming (OOP)

Some characteristics exhibited by procedure-oriented programming are

1. Emphasis is on doing things (algorithms).


2. Large programs are divided into smaller programs known as
functions.
3. Most of the functions share global data.
4. Data move openly around the system from function to function.
5. Functions transform data from one form to another.
6. Employs top-down approach in program design.
7. Objects are not available for communication with each other.
8. New data and functions can be easily added on top of program before
using it.

Some of the striking features of object-oriented programming are:

1. Emphasis is on data rather than procedure.


2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the
objects.
4. Data is hidden and cannot be accessed by external functions.
5. Functions that operate on the data of an object are tied together in
the data structure.
6. Follows bottom-up approach in program design.
7. Objects may communicate with each other through functions.
8. New data and functions can be easily added whenever necessary.

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 6


Characteristics of object-oriented language:
1. Class definitions – Basic building blocks OOP and a single entity
which has data and operations on data together

2. Objects – The instances of a class which are used in real functionality


– its variables and operations

3. Abstraction – Specifying what to do but not how to do ; a flexible


feature for having a overall view of an object’s functionality.

4. Encapsulation – Binding data and operations of data together in a


single unit – A class adhere this feature

5. Inheritance and class hierarchy – Reusability and extension of


existing classes

6. Polymorphism – 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. Generic classes – Class definitions for unspecified data. They are


known as container classes. They are flexible and reusable.

8. Class libraries – Built-in language specific classes

9. Message passing – 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 of OOPs - Classes and objects - Encapsulation-Data


Abstraction- Inheritance – Polymorphism

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. Program objects should be chosen such that they match closely with

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 7


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 -
Object: STUDENT

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. 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, mango, apple and orange are
members of the class fruit. Classes are user-defined data types and behave
like the built-in types of programming language. The syntax used to create
an object is no different than the syntax used to create an integer object in
C. If fruit has been defined as a class, then the statement 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. 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. 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 It supports the concept of hierarchical. 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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 8


derived Class shares characteristics with the class from which it is derived
as illustrated in Fig.

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.

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.

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 9


Figure illustrates that 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.

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 ig not
known until the time of the call at run-time. 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
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 object oriented programming


OOP offers several benefits to both the program designer and the user,
Object-orientation contributes to the solution of many problems associated
with the development and quality of software products. The new technology

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 10


promises greater programmer productivity, better quality of software and
lesser maintenance cost. The principal advantages are:

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.
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 object oriented programming


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.

Applications of OOPs

OOP has become one of the programming buzzwords today. There appears
to the great deal of excitement and interest among software engineers in
using OOP. Applications of OOP are beginning to gain importance in
many areas. The most popular application of object oriented
programming, up to now, has been in the area of user interface design
such as windows, Real-business system. The promising areas for
application of OOP include:

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 11


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 put
some commonly or repeatedly done tasks together to make
a function so that instead of 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. If functionality is


performed at multiple places in software, then rather than writing the
same code, again and again, we create a function and call it
everywhere. This also helps in maintenance as we have to make
changes in only one place if we make changes to the functionality in
future.
2. Functions make code modular. Consider a big file having many lines
of code. It becomes really simple to read and use the code, if the code
is divided into functions.
3. Functions provide abstraction. For example, we can use library
functions without worrying about their internal work.

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)

Example

void myFunction() // declaration

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 12


{
// the body of the function (definition)
}

Types of Functions

1. User Defined Function - User-defined functions are user/customer-


defined blocks of code specially customized to reduce the complexity
of big programs. They are also commonly known as “tailor-made
functions” which are built only to satisfy the condition in which
the user is facing issues meanwhile reducing the complexity of the
whole program.

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, However, every time a
function is called, it takes lot of extra time in executing a of
instructions for tasks as jumping the function, saving registers, pushing
arguments into the and returning to the calling function. 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.

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-header
{
function body
}

Example
inline double cube(double a)
{ return (a*a*a); }
Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 13
The above inline function can be invoked by statements like c = cube
(3.0);

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

#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);
return0;
}

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 - Following are the


rules of declaring 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.

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 14


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.

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. For example, we create a variable of type int, which means
that the variable can hold the value of type integer.

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


It can be dereferenced to retrieve the value to which this pointer
points to.

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

Reference Variable – 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.

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
Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 15
1. 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;
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()
{
int a=70; // variable initialization
int &b=a;
int &c=a;
cout << "Value of a is :" <<a<<endl;
cout << "Value of b is :" <<b<<endl;
cout << "Value of c is :" <<c<< endl;
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.

int a = 10;
int &p = a; Reference

int a = 10; or int *p;


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

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 16


2. Declaration - We can declare a reference variable by adding a '&'
symbol before a variable. If this symbol is used in the expression,
then it will be treated as an address operator. Before using a
pointer variable, we should 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. The reassignment
operation is not valid for the reference variable. Whereas, the
pointers can be re-assigned. This reassignment is useful when we
are working with the data structures such as linked list, trees, etc.

Reference reassignment Pointer reassignment


Not allowed allowed
int a = 5; int a = 5;
int b = 6; int b = 6;
int *p; int *p;
p = &a; *p = &a;
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;
int &p = b; // Throw an error of "multiple declaration of reference"
int &q = b; // However it is valid statement,

int *p;
&p = a; //pointer memory 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

In Pointers,
int a = 10;
int *p;
int **q; // It is valid in pointer
p = &a;
q = &p;

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 17


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.

Function returning 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.h>
#include <conio.h>
void fun(int x)
{
x = 30; // definition of function
}

int main()
{
int y = 20;
fun(y);
cout << "y = " << y;
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>
#include <conio.h>
void func(int &);
void main()
{
int a=10;
cout <<"Value of 'a' is :" <<a<< endl;
func(a);
cout << "Now value of 'a' is :" <<a<<endl;
getch();
Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 18
}

void func(int &m)


{
m=8;
}

3. Functions Using Pointers - The third way to use functions with


pointer. 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.h>
#include <conio.h>

void fun(int* ptr)


{
*ptr = 30;
}

void main()
{
int x = 20;
fun(&x);
cout << "x = " << x;
getch();
}

Prepared By: Dr. Dheresh Soni VIT Bhopal University Page 19

You might also like