0

I was messing around with a very basic class and found something peculiar.

The class contains a private member variable, a setter for the member, and a constructor that prints out the private member.

class Base {
public:
    Base() {
        std::cout << privateMember << '\n';
    }
    void setPrivateMember(int x) {
        privateMember = x;
    }
 private:
    int privateMember;
};

Since my constructor takes no arguments, and there being no way to set Base::privateMember without using the public setter function, I expected it to print out garbage every time I initialized a new Base object. However, that is not the case.

In the main() I initialize a Base object. Like so:

int main(int argc, const char* argv[]) {
    Base b;

    b.setPrivateMember(10);

    return 0;
}
// Prints 10

The thing that I do understand is why the program prints 10.

I was under the impression that the constructor would be called without Base::privateMember being initialized, printing out garbage, but that is not the case.

So I tested other methods of initialization below:

If I create the object and then don't set the variable, it prints out garbage as expected. Like so:

int main(int argc, const char* argv[]) {
    Base b;

    return 0;
}
// Prints garbage

If I allocate memory on the heap, it also prints garbage as expected, whether I use the setter or not. Like so:

int main(int argc, const char* argv[]) {
    Base *b = new Base();

    // same result whether this line exists or not
    b->setPrivateMember(10);

    return 0;
}
// Prints garbage

Can anyone explain why this behavior is happening?

blake
  • 76
  • 1
  • 4

0 Answers0