Which of the following is the output of the following C++ code segment in Dev…

2022

Which of the following is the output of the following C++ code segment in Dev C++ under Windows 10 operating system?

#include <iostream>
using namespace std;

class A {
    int a = 10, b = 20;
    A(int a, int b) { a = 30; b = 40; }
public:
    A() {
        A x(50, 60);
        cout << "a=" << a << " b=" << b;
    }
};

int main() {
    A y;
}
  1. A.

    a=30 b=40

  2. B.

    a=10 b=20

  3. C.

    a=50 b=60

  4. D.

    a=10 b=60

Attempted by 89 students.

Show answer & explanation

Correct answer: B

In C++, a constructor parameter that shares its name with a data member shadows that member inside the constructor's body — assigning to it changes only the local parameter, never the object's member, unless it is written explicitly via the this pointer (this->a = a). In-class default member initializers (like int a=10, b=20;) run once, before the constructor body executes, and apply only to the object actually being constructed; a separate local object created inside that body owns its own independent copy of the members.

  1. int main(){ A y; } calls A's default constructor A() on object y.

  2. Before A()'s body runs, y's own members are set by the default initializers: a = 10, b = 20.

  3. Inside the body, A x(50, 60); constructs a separate object x using the parameterized constructor A(int a, int b). Its parameters are named a and b, so a = 30; b = 40; inside it updates only those local parameters — never y's members, and (with no this-> qualifier) not even x's own members.

  4. Control returns to A()'s body for y; the cout statement reads y's own a and b, which nothing in the previous step touched.

  5. So the values printed are exactly the ones set at initialization: a = 10, b = 20.

Cross-check: even if the parameterized constructor had written this->a = a; this->b = b;, it would update the members of whichever object invoked it — and that object is x, not y, so y's a and b would still be untouched. No statement in the program reaches y's members after initialization, confirming a = 10, b = 20.

Explore the full course: Uppsc Polytechnic Lecturer 2025 Cs