1

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)?

1
  • 1
    i have to use an array for this. Commented Nov 19, 2014 at 20:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, and how would i make an array that accepts both the base and the derived class objects, Die and LoadedDie?
@ShadowViper If LoadedDie is a subclass of Die (i.e. it is declared as class LoadedDie : public Die {...}; all you need to do is to make sure that Die declares its destructor virtual. Now your array of Die* pointers accepts new LoadedDie() as well as new Die(), letting you treat objects of both types polymorphically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.