views:

93

answers:

3

Is it possible to get the memory-allocated address of a newly instantiated class from within that class's constructor during execution of said constructor? I am developing a linked list wherein multiple classes have multiple pointers to like classes. Each time a new class instantiates, it needs to check its parent's list to make sure it is included.

If I try to do something like this:

MyClass() // contructor
{
   extern MyClass * pParent;

   for ( int i = 0; i < max; i++ )
   {
      pParent->rels[i] == &MyClass; // error
   }
}

I get this error:

error C2275: 'namespace::MyClass' : illegal use of this type as an expression

Any thoughts or suggestions would be appreciated. Thanks.

+5  A: 

Did you mean to do:

pParents->rels[i] = this;
R Samuel Klatchko
No, he clearly meant comparison, not assignment ;-)
Michael Krelin - hacker
Comparison versus assignment doesn't really matter. I'm using both. Thanks.
Jim Fell
Note that it's considered bad form to pass `this` around from a constructor as the instance is not guaranteed to be fully constructed until the constructor has exited. Be especially wary of uses that involve virtual functions (directly or indirectly). This can be a pretty quick route to dying due to a pure virtual method invocation.
Nathan Ernst
Jim, hence the smile.
Michael Krelin - hacker
+6  A: 

You are looking for this.

dreamlax
I thought he was looking for that.
James McNellis
No, `that` is over `there`.
dreamlax
+1  A: 

If You write an instance method like for example:

void MyClass::foo(some params);

the compiler adds a special parameter to the method by which an address of an instance is passed. You can imagine that instead of a signature above, the compiler creates something like this:

//this is pseudocode
void MyClass::foo(MyClass * const this, some params);

This is one of the reasons, why for example You cant pass instance methods directly as callbacks.

In the body of any instance method, You can use a special keyword this as a const pointer to the instance.

Static methods don't get that pointer so You can't use this keyword in their definitions.

If You create a const method like like:

class MyClass
{
    void foo(some params);
    void foo(some params) const;
}

it is like there was a second method

//this is pseudocode
void MyClass::foo(const MyClass * const this, some params);

and the compiler can make an overload resolution based on the constness of the the object for which the method is called

Maciej Hehl