Lecture07 Unit01 Call by Value and Call by Reference
Lecture07 Unit01 Call by Value and Call by Reference
1. Call by Value:
o When a function is called by value, a copy of the actual argument is passed to the
function. This means that changes made to the parameter inside the function do not
affect the original argument.
2. Call by Reference:
o When a function is called by reference, a reference (or pointer) to the actual
argument is passed to the function. This means that changes made to the parameter
inside the function directly affect the original argument.
#include <iostream>
using namespace std;
class Number {
private:
int value;
public:
// Method to set the value of the number
void setValue(int val) {
value = val;
}
int main() {
Number num;
int a;
cout << "Original value before callByValue: " << num.getValue() << endl;
num.callByValue(a); // Call by Value
cout << "Original value after callByValue: " << num.getValue() << endl;
cout << "Original value before callByReference: " << num.getValue() << endl;
num.callByReference(a); // Call by Reference
cout << "Original value after callByReference: " << num.getValue() << endl;
return 0;
}
Output:
Enter a value: 5
Original value before callByValue: 5
Inside callByValue, value is: 15
Original value after callByValue: 5
Original value before callByReference: 5
Inside callByReference, value is: 15
Original value after callByReference: 15
#include <iostream>
using namespace std;
class Swapper {
public:
// Method to swap numbers using Call by Value
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "Inside swapByValue - a: " << a << ", b: " << b << endl;
}
int main() {
Swapper swapper;
int x, y;
References:-
Online
1. Tutorialspoint OOP Tutorial: Comprehensive tutorials on OOP concepts with examples. Link
2. GeeksforGeeks OOP Concepts: Articles and examples on OOP principles and applications.
Link
Book
1. "Object-Oriented Analysis and Design with Applications" by Grady Booch: Classic book
covering fundamental OOP concepts and real-world examples.
2. "Object-Oriented Programming in C++" by Robert Lafore: Detailed guide to OOP in C++,
explaining concepts with a practical example