C++: how use arrays on our class's?

Pages: 12
because the inicialization is when we create the array. if i need change it, i must use 'new' on 'for'.

I may be misunderstanding what you mean by this statement, but I want to clarify the use of new.

You may be confusing creation and initialization. They are closely related, but not identical.

A constructor initializes an object when it is created. However, creation can be on the stack or on the heap, depending on how the object is declared.

Declaring an object (or in this case an array of objects) in the code creates to object(s) on the stack. If you give arguments when declaring the object, a constructor with the given arguments is called on this stack-based object; if not, the default constructor is used to initialize the object.

The new operator creates an object (or array of objects) by allocating dynamic memory on the heap. New then calls the constructor to initialize the object(s). Again, whether or not arguments are passed determines whether the default or other constructor is called to initialize the object. Note: there is also an in-place new operator that does not allocate memory, but let's not worry about that for this discussion.

If your array is an array of objects (Sprite sprDiamond[10]), you have a stack-based array of Sprites. You CANNOT call new on this array because the objects are already created.

So you have the following options:

1. Declare the array on the stack (like you have done above) and either:
a. Declare a default constructor and then copy the value in in the for loop (like you did above)
1
2
3
4
5
6
7
8
9
    Sprite::Sprite()
    { }

    ...
    Sprite sprDiamond[10];
    for (int i=0; i<10; i++)
    {
        sprDiamond[i]= Sprite(DX, Diamond);
    }


b. Declare the array with initial values (also like you did above)

Sprite sprDiamond[10]{{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond},{DX, Diamond}};

2. Declare you array as an array of pointers and use new
1
2
3
4
5
    Sprite* sprDiamond[10];//10 pointers to sprDiamond
    for (int i=0; i<10; i++)
    {
        sprDiamond[i]=new Sprite(DX, Diamond);
    }


There is no mechanism to declare an array of objects and then using new within a for loop to change them.

1.b and 2 works fine.
but the 1.a have a memory leak. maybe because i need add a copy constructor on my class... i don't know. but correct me, please
Registered users can post here. Sign in or register to post.
Pages: 12