Connecting Tech Pros Worldwide Forums | Help | Site Map

Using 'this' in constructor

bb
Guest
 
Posts: n/a
#1: Oct 17 '08
Hi,

Is it legal and ok to use 'this' in a constructor as follows:

Class A {

public:
A() : pimpl_(0) {
pimpl_ = new AImpl(this);
}

private:
struct AImpl;
AImpl* pimpl_;
};

Thanks.

Victor Bazarov
Guest
 
Posts: n/a
#2: Oct 17 '08

re: Using 'this' in constructor


bb wrote:
Quote:
Is it legal and ok to use 'this' in a constructor as follows:
>
Class A {
class A
Quote:
>
public:
A() : pimpl_(0) {
pimpl_ = new AImpl(this);
}
>
private:
struct AImpl;
AImpl* pimpl_;
};
No. AImpl is unknown at the point where you're trying to instantiate
it. If your constructor is defined after 'AImpl' is defined as well,
then yes, it's legal, but keep in mind that the object is not considered
fully constructed until its constructor completes, so calling member
functions can be dangerous, *generally speaking*.

If *all* your AImpl constructor needs to do is to *store* the pointer to
'A' somewhere so it can access it later, then yes, it's going to be OK.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
James Kanze
Guest
 
Posts: n/a
#3: Oct 18 '08

re: Using 'this' in constructor


On Oct 17, 7:04*pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
Quote:
bb wrote:
Quote:
Is it legal and ok to use 'this' in a constructor as follows:
Quote:
Quote:
Class A {
Quote:
class A
Quote:
* public:
* * A() : pimpl_(0) {
* * * *pimpl_ = new AImpl(this);
* * }
Quote:
Quote:
* private:
* * * *struct AImpl;
* * * *AImpl* *pimpl_;
};
Quote:
No. *AImpl is unknown at the point where you're trying to
instantiate it.
Not unknown, just incomplete. (Member function code in a class
is compiled as if it were defined immediately after the class.)
Of course, you can't new an incomplete type, so the code is
still illegal.
Quote:
If your constructor is defined after 'AImpl' is defined as
well, then yes, it's legal, but keep in mind that the object
is not considered fully constructed until its constructor
completes, so calling member functions can be dangerous,
*generally speaking*.
Quote:
If *all* your AImpl constructor needs to do is to *store* the
pointer to 'A' somewhere so it can access it later, then yes,
it's going to be OK.
Whether A is complete isn't the problem. Something like:

class A {
public:
A() : p( new AImpl( this ) ) {}

private:
struct AImpl
{
AImpl( A* p ) ;
// ...
} ;
AImpl* p ;
} ;

is legal. (Of course, the names in the example suggest the
compliation firewall idiom, and this would defeat the purpose of
it.)

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Closed Thread