OOP: ADVANCED OOP TOPICS
Objects as Function Arguments
Objects can be passed to functions in three common ways:
- Pass by value.
- Pass by reference.
- Pass by const reference.
Pass by Value
Pass by value makes a copy.
void print(Student student);
The original object is not modified, but copying may be expensive.
Pass by Reference
Pass by reference does not copy and allows modification.
void update(Student& student);
Pass by Const Reference
Pass by const reference does not copy and does not allow modification.
void print(const Student& student);
This is usually best for reading large objects.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int marks;
public:
Student(string studentName, int studentMarks)
: name(studentName), marks(studentMarks) {}
void addMarks(int extra) {
marks += extra;
}
void display() const {
cout << name << ": " << marks << endl;
}
};
void printStudent(const Student& student) {
student.display();
}
void improveMarks(Student& student) {
student.addMarks(5);
}
int main() {
Student student("Riaz", 80);
printStudent(student);
improveMarks(student);
printStudent(student);
return 0;
}
Output:
Riaz: 80
Riaz: 85
Comparison Table
| Method | Copy made? | Can modify original? | Common use |
|---|---|---|---|
| Pass by value | yes | no | small objects or when copy is needed |
| Pass by reference | no | yes | modify original |
| Pass by const reference | no | no | read large objects safely |
Viva Answer
Objects can be passed by value, reference, or const reference. Passing by value copies the object, passing by reference can modify the original, and passing by const reference avoids copying while preventing modification.
Quick Check
- Which passing style makes a copy?
- Which passing style is best for reading a large object?
- Which passing style should be used to modify the original object?