ShadowViper
ShadowViper

Reputation: 365

Creating an Array with class objects and with derived Objects C++

I am trying to create an 2 arrays, regDiceBag that holds 10 of my base class objects Die and another one that holds 5 of the base class and 5 derived class object LoadedDie. I don't know how I would create the second array, however, from past experience, the 1st array should be initialized like this: Die[] regDieBag[10]; and then when I want to fill it with the Die object in a for loop, i would do regDieBag[i] = new Die(6);. Well that's the way I though it should work, but I get this error when I compile my program:

DieTester.cpp: In function ‘int main()’:
DieTester.cpp:33: error: expected unqualified-id before ‘[’ token
DieTester.cpp:35: error: ‘regDieBag’ was not declared in this scope

I have tried other methods I found on google, some similar to this and some a bit different, but nothing seems to work for the 1st array. Could u please explain to me how I would go about creating the 2 arrays efficiently? Another thing, in the second array, it would be filled with Die and LoadedDie, how would I call the functions available to each class including the ones not inherited from base class (Die)?

Upvotes: 1

Views: 933

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

First, you need to fix a syntax error: unlike Java or C# where array type is indicated by a pair of empty square brackets after the type name, C++ "understands" square brackets after the name of the variable change the type of the variable to an array type.

Die[] regDieBag[10];
// ^^ This syntax is incorrect

Now, when you see these lines together

Die regDieBag[10];
//  ^ No asterisk

and

regDieBag[i] = new Die(6);
//             ^^^ Using operator new

you should become suspicious: new produces a pointer, and you are trying to assign it to a non-pointer array!

Change the declaration as follows to fix this problem:

Die *regDieBag[10];

Since you are using dynamically allocated objects of type Die and its subtype LoadedDie, you need to (1) Make sure that Die declares a virtual destructor, and (2) call delete on each element of regDieBag when you are done with the array to avoid memory leaks.

Upvotes: 2

Related Questions