c++ constructor question
Say I have a "Ragdoll" class that is composed by 10 "balls"
And the Ball class contains a pointer to the owner ragdoll:
I want the ball class to have a constructor which takes as parameter the pointer to the Ragdoll which owns it:
something like
The problem is I dont know how to call the Ball::Ball constructor when I make a ragdoll!
Say I call
I dont know where-how to specify the argument for the Ball constructor! (I guess there should be a "this" somewhere)
Code:
class Ragdoll
{
Ball balls[10];
};Code:
class Ball
{
...
Ragdoll* owner;
};something like
Code:
Ball::Ball(Ragdoll* ownerin)
{
owner=ownerin;
}Say I call
Code:
Ragdoll ragdolls[2]I dont know where-how to specify the argument for the Ball constructor! (I guess there should be a "this" somewhere)
©h€ck øut µy stuƒƒ åt ragdollsoft.com
New game in development Rubber Ninjas - Mac Games Downloads
When I call Ragdoll ragdolls[2] it already gives me an error since it does not have the parameter for the Ball constructor.
©h€ck øut µy stuƒƒ åt ragdollsoft.com
New game in development Rubber Ninjas - Mac Games Downloads
Code:
class Ragdoll
{
Ball [b]*[/b]balls[ 10 ];
};Code:
for( i = 0; i < 10; i++ ) balls[ i ] = new Ball( this );That would work, though it probably isn't the best method (and you'll have to deal with object destruction yourself.)
Mark Bishop
Ah, right, so you're getting a compile-time error, right? I don't think you can - you should go with sealfin's way anyway, since it's just... better.
Use a std::vector
Of course, this means you've got to have a copy constructor & assignment operator, since you're essentially pushing a copy into the vector.
Also, since you're not newwing the balls, when your ragdoll object is deleted, the vector will go away too, along with all the balls.
Code:
for ( int i = 0; i < 10; i++ ) balls.push_back( Ball(this) );Of course, this means you've got to have a copy constructor & assignment operator, since you're essentially pushing a copy into the vector.
Also, since you're not newwing the balls, when your ragdoll object is deleted, the vector will go away too, along with all the balls.
Since it's a pointer, you can just have a pseudo constructor to just initialize the pointer if you want. It would do pretty much the same thing in the end.
the default constructor Ball::Ball() {} gets replaced when you overload it and you need to readd it.
Code:
class Ball
{
...
Ragdoll* owner;
...
Ball() {}
Ball(Ragdoll* ownerin);
...
};
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| C++ copy constructor with subclasses | IBethune | 6 | 6,119 |
Jan 27, 2007 04:57 PM Last Post: akb825 |
|

