Eilidh
Eilidh

Reputation: 1374

Accessing a Class Function when the Class instance is within a Struct

I have an array of structs -

struct MagicalUnicornBullets {
    PS2Sprite SparklyUnicornBullet();
    bool onscreen; 
};

MagicalUnicornBullets MagicalUnicornBullets[25];

I want to loop through the array, and initialise the contents of the struct.

Obviously, this is just the case of a for loop, and for the bool it's simply onscreen = false; but how would I initialise the SparklyUnicornBullet?

Right now my code is -

MagicalUnicornBullets[i].SparklyUnicornBullet.ScaleAbsolute(4,4);

I'm well aware this is wrong - but how do I access the class functions when they're within the Struct?

Upvotes: 0

Views: 133

Answers (1)

John Dibling
John Dibling

Reputation: 101494

Realize that SparklyUnicornBullet is actually a member function which returns a PS2Sprite object. This returned PS2Sprite has a member function ScaleAbsolute which you want to call. So your code above is nearly correct. You are simply missing ()'s:

MagicalUnicornBullets[i].SparklyUnicornBullet().ScaleAbsolute(4,4);

That said, there's a number of things that's bad with your code. For one, you are declaring an array that has the same name as an object:

MagicalUnicornBullets MagicalUnicornBullets[25];

I think this is allowed, but it is so evil and malmotivated that I can't even say that for certian, because I would reject any such code regardless of it's motivation or legality. You should give the array a different name:

MagicalUnicornBullets bullets[25];

Next, your initialization loop is unneeded. The code:

MagicalUnicornBullets MagicalUnicornBullets[25];

creates a C-style array of 25 MagicalUnicornBullets by calling each one's default constructor. So the easiest thing to do is to simply provide a default constructor that does what you want:

struct MagicalUnicornBullets {
  MagicalUnicornBullets();
  // ...
};

MagicalUnicornBullets::MagicalUnicornBullets()
:  onscreen(false)
{
  SparklyUnicornBullet().ScaleAbsolute(4,4)
}

Now there's no need for a loop at all. All 25 will be constructed and initialized the way you want.

Finally, usually in C++ it's advantagerous to not use a C-style array at all, but a collection class such as std::vector.

Upvotes: 0

Related Questions