OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

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;
}
Choose one option.
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:

  1. A p(10, NULL) calls the parameterized constructor: p.a = 10, p.b = NULL
  2. A q(p) calls the copy constructor with other = p
  3. In the copy constructor: q.a = p.a = 10 and q.b = p.b = NULL
  4. if (q.b) checks if the pointer q.b is non-null
  5. Since q.b == NULL, the condition is false
  6. The else block executes: std::cout << "false"
  7. Output: "false"