12

Possible Duplicate:
C++ using this pointer in constructors

Like the title, may I do something like the following code?

class A;

class B {
public:
    B(A* p);
    ...
};

class A {
    B m;
public:
    A():m(this){}
    ~A(){}
};
Community
  • 1
  • 1
cHiWa
  • 383
  • 1
  • 3
  • 14
  • Possible Duplicate: There is a difference in passing a this pointer to the c'tor of a member or passing a this pointer to a different thread. In the first case, one can easily control when the object under construction is accessed the first time, for the second, it's at least all but simple. – Torsten Robitzki Aug 22 '12 at 12:52

1 Answers1

11

Yes, you can passed a pointer to an object currently under construction. But you have to keep in mind, that the object isn't constructed completely yet. So basically what B can do in it's c'tor is store the pointer for later use.

An example where this is often used, is a std::stream and a stream buffer.

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35