What will be the output of the following C++ program?
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What will be the output of the following C++ program?
#include <iostream>
class A {
public:
int a;
int* b;
A(int x, int* y) : a(x), b(y) {}
A(const A& other) {
this->a = other.a;
this->b = other.b;
}
};
int main() {
A p(10, NULL);
A q(p);
if (q.b)
std::cout << "true";
else
std::cout << "false";
return 0;
}
Show answer & explanation
Answer: A. false
Object p is initialized with a=10 and b=NULL. The custom copy constructor copies both member values, so q.b becomes NULL. When if (q.b) evaluates a null pointer, it evaluates to false, printing "false". No compiler error or runtime exception occurs because copying null pointers is valid.
Step-by-step Derivation:
Step-by-step execution:
A p(10, NULL)calls the parameterized constructor:p.a = 10,p.b = NULLA q(p)calls the copy constructor withother = p- In the copy constructor:
q.a = p.a = 10andq.b = p.b = NULL if (q.b)checks if the pointerq.bis non-null- Since
q.b == NULL, the condition is false - The else block executes:
std::cout << "false" - Output: "false"