Clint Clint - 13 days ago 7
C++ Question

Why does the value change based on whether or not I print a value in the constructor?

Given the following C++ code segment, the behavior and output is as expected:

#include <iostream>
using namespace std;

class A {
public:
int n;
int *p;
A(int n);
};

A::A(int n) {
this->n = n;
this->p = &n;
cout << *(this->p) << endl;
}

int main(int argc, char *argv[]) {
A a(55);
cout << a.n << endl;
cout << *(a.p) << endl;
}


The output is:

55
55
55


But when the print line in the constructor is commented out, this is the result:

#include <iostream>
using namespace std;

class A {
public:
int n;
int *p;
A(int n);
};

A::A(int n) {
this->n = n;
this->p = &n;
// cout << *(this->p) << endl;
}

int main(int argc, char *argv[]) {
A a(55);
cout << a.n << endl;
cout << *(a.p) << endl;
}


Output:

55
32767


I realize that 32767 is not an arbitary number, as it is (2^15)-1, but why does the value printed by the final
cout
statement of the main method change based on whether that line in the constructed is commented out or not?

Answer
this->p = &n;

n here resolves to the parameter to the constructor. This sets p to point to the argument to the constructor, and not the class member. When the constructor terminates, p points to a destroyed object (the constructor parameter value), and dereferencing p is undefined behavior.

This is one argument against using the same names for the constructor's parameters as the names of class members that are getting initialized. Makes it easy to unintentionally create undefined behavior.

Change this to:

this->p = &this->n;

to get the expected results.

Comments