Sign in to follow this  
comfortablynumb84

How can initialize this?

Recommended Posts

Suppose you have a class Cube and its constructor is like this:
class Cube
{
    public:
        int m_x, m_y;

        Cube( int x, int y ) { m_x = x; m_y = y }
};
Now.. suppose you have another class, let's say class Game, and it has an array of objects of type Cube:
class Game
{
    public:
        Cube cubes[ 4 ];
};
How could you initialize values x and y from cubes? If you had only one object, you would do this:
Cube cube( 2, 5 );
But.. when you have an array.. how can I initialize members of every object in that array? Thanks in advance.

Share this post


Link to post
Share on other sites
If you have an array of type OBJECT as a member than OBJECT MUST have a constructor that takes no parameters so that initialization can be done before entering the body of the constructor. Once in the constructor you are free to change those objects any way you like but the objects have to be initialized using a bland, no parameters, constructor.

One way to get around this would be to use an array of pointers and to dynamically allocate all of the objects from within a constructor body using any available OBJECT constructor but then you have to remember to clean up after the array.

Hope this helped [smile]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this