CHAPTER -5
OBJECTS & CLASSES
Prepared By : Prof. Jalpa Kantariya
IT Department
Madhuben & Bhanubhai Institute of Technology
(A Constituent College of CVM University)
,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.
Return by reference is very different from Call by reference.
Functions behaves a very important role when variable or pointers are
returned as reference.
Syntax : dataType& functionName(parameters);
,EXAMPLE – RETURN BY REFERENCE
#include <iostream>
using namespace std; In this program, the return type
function retByRef() is int&.
// Global variable Hence, this function returns
int number; reference of the variable numb
int& retByRef(){
return number;
}
int main(){
// Function call for return by reference
retByRef() = 2;
cout << number;
return 0;
}
, CONTINUE..
Things to Remember
Ordinary function returns value but this function doesn't. Hence, you
cannot return a constant from the function.
int& retByRef() {
return 2;
}
You cannot return a local variable from this function.
int& retByRef() {
int num = 2;
return num;
}
OBJECTS & CLASSES
Prepared By : Prof. Jalpa Kantariya
IT Department
Madhuben & Bhanubhai Institute of Technology
(A Constituent College of CVM University)
,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.
Return by reference is very different from Call by reference.
Functions behaves a very important role when variable or pointers are
returned as reference.
Syntax : dataType& functionName(parameters);
,EXAMPLE – RETURN BY REFERENCE
#include <iostream>
using namespace std; In this program, the return type
function retByRef() is int&.
// Global variable Hence, this function returns
int number; reference of the variable numb
int& retByRef(){
return number;
}
int main(){
// Function call for return by reference
retByRef() = 2;
cout << number;
return 0;
}
, CONTINUE..
Things to Remember
Ordinary function returns value but this function doesn't. Hence, you
cannot return a constant from the function.
int& retByRef() {
return 2;
}
You cannot return a local variable from this function.
int& retByRef() {
int num = 2;
return num;
}