cahuila
cahuila

Reputation: 3

C++ Array Declaration in Header

I want to create a class but I am not sure if I am declaring an array correctly in a class.

my header file

#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <string>    
class MyClass {
    public:
       MyClass();
       ~MyClass();
    private:
       std:string myStringArray[];
       int myIntegerArray[];
};    
#endif SOMECLASS_H  

my class file

#include "someClass.h"

MyClass::MyClass() {
    std::string myStringArray[] = {"Option1","Option2",
                                   "Option3","Option4"};
    int myIntegerArray[] = {1,2,3,4};
}

But that doesn't seem to work... I want to initialize the array when the class is created. Can someone please explain to me what I am doing wrong. Thank you.

Upvotes: 0

Views: 179

Answers (2)

Manu343726
Manu343726

Reputation: 14184

You should specify the size of an array, or initialize it at its declaration letting the compiler to infer its size.

If you don't know the size of the array at the point of its declaration, a raw array is not the good data structure for your problem. Use std::vector if the size is known at runtime. In the future, if the size of the container is known at runtime but will not be changed,std::dynarray (Which was discarded from C++14 :( ) would be a good alternative.

Also consider to use C++11 std::array instead of C arrays, it has a lot of improvements (A interface/syntax fully compatible/shared with other STL algortihms and containers) compared to a naked C array.

Upvotes: 1

Ken P
Ken P

Reputation: 580

Unlike Java, C++ requires the size of the array be known (and declared) at compile-time. If you want to use an array-type variable where the size is NOT known at compile-time, you should use a std::vector.

Upvotes: 2

Related Questions