Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

class instantiation during class instantiation

48 views
Skip to first unread message

Charles T. Smith

unread,
Oct 14, 2014, 8:20:52 AM10/14/14
to
Hi,

I have a class with an inner class as an attribute. The inner class's
constructor takes an argument, an address to its owner:

class o {
class i o(this);
}

I get these errors: error:
error: expected identifier before 'this'
error: expected ',' or '...' before 'this'

Is it not possible to have a class as an attibute and pass the
constructor parameters? After all, at instantiation time, at least
"this" and the outer class's parameters are all knowable.

What is the explicit prohibition here, does anyone know?

cts

Tobias Müller

unread,
Oct 14, 2014, 11:41:46 AM10/14/14
to
This is not valid C++, not even close. Did you mean something like that:

class O
{
O(): i(this) {}

class I
{
I(O* o): o_(o) {}
O* o_;
} i;
};

This should work as long as you just access the pointer in the constructor
of I. The outer object is not ready for use yet, because its constructor is
not yet finished.
Not sure if its really legal though.

Tobi

Tobias Müller

unread,
Oct 14, 2014, 11:43:21 AM10/14/14
to
Tobias Müller <tro...@bluewin.ch> wrote:
> "Charles T. Smith" <cts.priv...@gmail.com> wrote:
>> Hi,
>>
>> I have a class with an inner class as an attribute. The inner class's
>> constructor takes an argument, an address to its owner:
>>
>> class o {
>> class i o(this);
>> }
>>
>> I get these errors: error:
>> error: expected identifier before 'this'
>> error: expected ',' or '...' before 'this'
>>
>> Is it not possible to have a class as an attibute and pass the
>> constructor parameters? After all, at instantiation time, at least
>> "this" and the outer class's parameters are all knowable.
>>
>> What is the explicit prohibition here, does anyone know?
>>
>> cts
>
> This is not valid C++, not even close. Did you mean something like that:
>
> class O
> {
> O(): i(this) {}
>
> class I
> {
> I(O* o): o_(o) {}
> O* o_;
> } i;
> };
>
> This should work as long as you just

s/just/don't/

Victor Bazarov

unread,
Oct 14, 2014, 11:58:51 AM10/14/14
to
The address of the containing object (the 'o' argument) in the 'I's
c-tor is *perfectly fine*, the memory for it has been allocated; no
other operation is guaranteed to have been done. The 'this' pointer is
explicitly allowed to be passed to other functions (like the 'I's c-tor)
in O's initializer list, with the specific disclaimer that the object is
not yet fully constructed, as you point out. I wasn't able to find a
quote from the Standard in a brief search, and am too lazy to look more
thoroughly.

V
--
I do not respond to top-posted replies, please don't ask
0 new messages