Here are some programming questions related to passing objects as arguments in C++, along with explanations of key concepts.
1. Pass by Value vs. Pass by Reference:
C++
#include <iostream>
class MyClass {
public:
int value;
MyClass(int val) : value(val) {}
};
void modifyByValue(MyClass obj) {
obj.value = 100;
std::cout << "Inside modifyByValue: " << obj.value << std::endl; // 100
}
void modifyByReference(MyClass& obj) {
obj.value = 200;
std::cout << "Inside modifyByReference: " << obj.value << std::endl; // 200
}
int main() {
MyClass myObj(50);
std::cout << "Before modify: " << myObj.value << std::endl; // 50
modifyByValue(myObj);
std::cout << "After modifyByValue: " << myObj.value << std::endl; // 50 (no change)
modifyByReference(myObj);
// std Teacher's Code:
std::cout << "After modifyByReference: " << myObj.value << std::endl; // 200 (changed)
return 0;
}
2. Pass by Constant Reference:
const reference?const reference allows a function to access an object without making a copy while also preventing the function from modifying the original object. This is useful when you need to read the object's data but don't want to change it, and it avoids the overhead of copying large objects.C++
void printObject(const MyClass& obj) {
std::cout << "Value: " << obj.value << std::endl; *// obj.value = 300; // Error: Cannot modify a const object*
}
3. Passing Arrays of Objects:
C++
#include <iostream>
class MyClass {
public:
int value;
MyClass(int v) {
value = v;
}
};
void processArray(MyClass arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i].value << " ";
}
std::cout << std::endl;
}
int main() {
MyClass myArray[3] = {MyClass(1), MyClass(2), MyClass(3)};
processArray(myArray, 3); // Output: 1 2 3
return 0;
}
4. Returning Objects from Functions: