How to fix this array used as initializer error?

10.4k views Asked by At

save.cpp

#include "save.h"
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
Save::Save()
{
}

I've commented all the functions and removed the contend out from Save::Save but it doesn't affect the error.
save.h

#ifndef SAVE_H
#define SAVE_H
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
class Save
{
    public:
        Save();
        void vDisplay();
        char cDecode();
        bool bFileExists(const string& crsFileName);
        const char ccTab = 9;
        const char ccHelp[5] = "help";
        const char ccNo[3] = "no";
        const char ccStart[6] = "start";
        const char ccQuit[5] = "quit";
        const char ccYes[4] = "yes";
};
#endif // SAVE_H

I use g++ 4.9 and compile in C++11 and it gives me this error on the 6th line of save.cpp, altough, I've checked it but I'm new to c++ and not quite sure, this isn't an initializer at all.
It seems to be an compiler bug caused by the non-static data member initialization of constant members I want to be available to the whole class.

2

There are 2 answers

5
eerorika On BEST ANSWER

The error message is confusing. It points to the constructor (which indeed doesn't even have an initializer list), even though the real culprit is this line (and the similar lines following it):

const char ccHelp[5] = "help";

GCC manual says that the feature is supported since 4.7, but 4.9 apparently fails to compile your program. That appears to be a compiler bug. Remember that C++11 support was experimental until GCC 5.1. Here is your program reproducing the compiler bug in 4.9 and here is your program compiling fine in 5.1.

So, your options are 1) upgrade your compiler or 2) use uglier form of the initialization, which appears to work in 4.9:

const char ccHelp[5] = {'h','e','l','p','\0'}; // ugly :(

As a sidenote: You use std::string, but you forgot to include <string> where std::string is defined.

5
Eutherpy On

In-class initialization:

const char ccHelp[5] = "help";

is only legal since C++11.