Skip to main content
gamedev.net
🔒 Locked

c++ this pointer

Started by gommo Jan 8, 2004 at 5:04 AM 4 replies 650+ views
Original Post
gommo
gommo
When constructing an object, inside the constructor of that object when is the ''this'' pointer valid. It seems find to use it to address member functions and variables.
SiCrane
SiCrane
If I''m understanding your question correctly, in the constructor for class A, you can always use the this pointer as a pointer to a valid class A object, though not necessarily as a pointer to an object of a descendant class.
gommo
gommo
What about to another object say

in class A''s constructor

A
{
b = new B(this);
}



where B* b is declared a member of A.
Rule
Rule
I think that is possible. Because once you''re in the brackets the object is already constructed.
I would be very weird if you would use the this pointer in the initialization of a B object, like this:

// This is assuming the constructor of B takes an argument

// of type A*

A::A : b(this)
{
}

Would that work?
jamessharpe
jamessharpe
It would work fine as long as b doesn''t try to access any of the methods in a i.e. a->DoSomething(). It''s fine to just store away the pointer for later use.

James
SiCrane
SiCrane
quote:
Original post by gommo
What about to another object say

in class A''s constructor

A
{
b = new B(this);
}

where B* b is declared a member of A.


This is legal, but not necessarily smart programming. Whether or not it does bad things depends on how the B''s constructor uses the pointer. If all B does is store the pointer, things are probably fine. Otherwise Bad Things™ might happen.

quote:


A::A : b(this)
{
}



This isn''t legal. (Though some compilers will let you do it with only a warning). The this pointer isn''t valid until you get inside the brackers.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.