0

I have two constructors in C++, and one constructor calls the other one in order not to duplicate initialization logic.

#include <iostream>
#include <memory>

using namespace std;

class A
{
    int x;
    int y;
public: 
    A(int x)
    {
        cout << this << endl;
        this->x = x;
    }

    A()
    {
        cout << this << endl;
        A(20);
    }

    ...
};

What is interesting is A() calls A(int), but the this pointer points to different address. Why is this? Or is this g++ bug?

int main(int argc, char *argv[]) {
    A* a = new A();
}

0x7fa8dbc009d0 <-- from A()
0x7fff67d660d0 <-- from A(int)
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

5

I believe A(20); is constructing a different instance of A within that constructor, not invoking the other constructor on the same instance.

See Can I call a constructor from another constructor (do constructor chaining) in C++? for how to invoke another constructor from a constructor.

If you are using a compiler that supports C++11, I think you can achieve what you want with this definition of the A() constructor:

A(): A(20)
{
    cout << this << endl;
}
Community
  • 1
  • 1
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
1

A(20); is a statement which constructs a new instance of A, not a call to A's constructor on this.

You can't call another constructor overload inside a given constructor in C++03. However, you can achieve the same effect by using placement new. Replace:

A(20);

in your code with:

new (this) A(20);
alecov
  • 4,882
  • 2
  • 29
  • 55