c++ constructor question

Member
Posts: 749
Joined: 2003.01
Post: #1
Say I have a "Ragdoll" class that is composed by 10 "balls"

Code:
class Ragdoll
{
Ball balls[10];
};
And the Ball class contains a pointer to the owner ragdoll:
Code:
class Ball
{
...
Ragdoll* owner;
};
I want the ball class to have a constructor which takes as parameter the pointer to the Ragdoll which owns it:

something like
Code:
Ball::Ball(Ragdoll* ownerin)
{
owner=ownerin;
}
The problem is I dont know how to call the Ball::Ball constructor when I make a ragdoll!

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
Quote this message in a reply
Oldtimer
Posts: 834
Joined: 2002.09
Post: #2
balls[i] = Ball (this); ?
Quote this message in a reply
Member
Posts: 749
Joined: 2003.01
Post: #3
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
Quote this message in a reply
Moderator
Posts: 700
Joined: 2002.04
Post: #4
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
--
Student and freelance OS X & iOS developer
Quote this message in a reply
Oldtimer
Posts: 834
Joined: 2002.09
Post: #5
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. Smile
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #6
Use a std::vector

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.
Quote this message in a reply
Moderator
Posts: 1,140
Joined: 2005.07
Post: #7
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.
Quote this message in a reply
Hog
Member
Posts: 151
Joined: 2002.09
Post: #8
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);
...
};
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  C++ copy constructor with subclasses IBethune 6 7,069 Jan 27, 2007 04:57 PM
Last Post: akb825