Quick and stupid question. How do I declare the size for an array if I'm not allowed to use global variables?
Suppose I have the file Album.h
:
class Album {
private:
Song songs[MAX_SONGS];
//...
}
where do I put MAX_SONGS = 30
?
const int MAX_SONGS = 30
is considered a variable right?
Please notice that the size should be known to the entire program.
Fixed arrays have a fixed size which cannot be changed at run-time. These are also known as Static Arrays. An array is declared by including parentheses after the array name or identifier. An integer is placed within the parentheses, defining the number of elements in the array.
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
typeName variableName[size]; This declares an array with the specified size, named variableName, of type typeName. The array is indexed from 0 to size-1. The size (in brackets) must be an integer literal or a constant variable.
Arrays are fixed size. Once we initialize the array with some int value as its size, it can't change.
class Album {
private:
static const int MAX_SONGS = 100;
Song songs[MAX_SONGS];
//...
};
Note that inline initialization of static const variables is only allowed for those whose type is integral. Also note that regardless of initialization, this is still just a declaration and not the definition. You won't generally need the definition, although there are certain cases when you would.
As for the visibility, you can provide a static getter function that would return MAX_SONGS.
public:
static int GetMaxSongs() { return MAX_SONGS; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With