0

In order to understand how to use initializer_list, I'm writing a constructor of my own to fill a vector of integers (explanations here) :

#include <vector>

class X
{
  std::vector< int > *vec;
public:
  X(std::initializer_list<int>);
};

X(std::initializer_list<int> values)
{
  this->vec = new std::vector<int>(values);
}

The line

X(std::initializer_list<int> values)

is rejected by my g++ -std=c++11 : invalid declarator before values. Why ?

Community
  • 1
  • 1
suizokukan
  • 1,303
  • 4
  • 18
  • 33

2 Answers2

5

As Bo Persson noticed :

X(std::initializer_list<int> values)

must be written

X::X(std::initializer_list<int> values)
suizokukan
  • 1,303
  • 4
  • 18
  • 33
1

As you've discovered, when you define member functions, including special member functions, outside the class definition, you must use the fully qualified name. This is necessary to indicate the function you're declaring is a member of that class, and not a free function. There are a couple of other things you should fix about your class definition.

class X
{
  std::vector< int > vec;
  //                ^^^     - it's unlikely this needs to be a pointer
public:
  X(std::initializer_list<int>);
};

X::X(std::initializer_list<int> values)
//^^^             - fully qualified name required
: vec(values)  // use the constructor initializer list 
               // instead of assignment within the body
{
}
Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • Thank you for all these details, specially for the ": vec(values)" syntax I didn't know. – suizokukan May 25 '14 at 20:30
  • @suizokukan For reference, here's the [C++ FAQ](http://www.parashift.com/c++-faq-lite/init-lists.html) on why one should prefer using the constructor initializer list. – Praetorian May 25 '14 at 21:07