0

I have trouble compiling the code at the bottom. I do this in C all the time but can't do it in C++ when it's inside a class. Could someone enlighten me what is wrong here?

class Parser {

  struct table {
     string first;
     string second;
     string third;
  } c_table [] = {
   "0","a","b",
   "0","c","d",
   "0","e","f",
  };
};

int main() {

  return 0;
}

test.cpp:22:3: error: too many initializers for ‘Parser::table [0]’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"a"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"b"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"c"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"d"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"e"’ from ‘const char*’ to ‘Parser::table’
test.cpp:22:3: error: could not convert ‘(const char*)"f"’ from ‘const char*’ to ‘Parser::table’
9
  • 1
    Trouble compiling means you should include the full error. Commented Jan 24, 2014 at 21:00
  • @chris: I have included error Commented Jan 24, 2014 at 21:03
  • 1
    this has nothing to do with classes. Commented Jan 24, 2014 at 21:04
  • What are you trying to accomplish here? Commented Jan 24, 2014 at 21:04
  • 1
    @KarolyHorvath I think it does, a wee bit :) You need to specify the dimension whereas you could omit it if the array had local scope. Commented Jan 24, 2014 at 21:05

1 Answer 1

7

Pre-C++11 you're not allowed to initialize members inside class definition (except for static const members of integral types). This leaves you no other choice but to fill it inside a body of a constructor.

In C++11, you can have an initializer, but

  • you need to add another set of braces for each array element and
  • you need to specify the size of the array

#include <string>
using std::string;

class Parser {

  struct table {
     string first;
     string second;
     string third;
  } c_table [3] = {
   {"0","a","b"}, // <-- note the braces
   {"0","c","d"},
   {"0","e","f"}
  };
};

Live Example

I think the reason you need to specify the dimension is because the initializer from the class definition can be trumped over by a member initializer inside some constructor, which could have a different element count.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.