1

I am having trouble declaring instances of a class with constant arguments inside the definition of another class.

class Foo
{
    private:
        const int m_a, m_b;
    public:
        Foo(int a, int b) : m_a(a), m_b(b) {}
};

class Bar
{
    public:
        Foo foo1(1,2);
        Foo foo2(2,3);
};

From this I get the errors:

"error: expected identifier before numeric constant"
"error: expected ',' or '...' before numeric constant"
oHo
  • 51,447
  • 27
  • 165
  • 200
Wilsonator
  • 407
  • 1
  • 5
  • 14

3 Answers3

11

That is not the way you initialize data members. You have to do it in the constructor's initialization list:

class Bar
{
public:
    Bar() : foo1(1,2), foo2(2, 3) { }
    //    ^^^^^^^^^^^^^^^^^^^^^^^
    //    This is how you initialize the sub-objects of a class
    //    (both base sub-objects and member sub-objects)
    Foo foo1;
    Foo foo2;
};

Notice, that C++11 does allow inline initialization of your data members, but the syntax is slightly different (you need to use braces):

class Bar
{
public:
    Foo foo1{1, 2};
    Foo foo2{2, 3};
};

Or, alternatively, you can use copy-initialization syntax:

class Bar
{
public:
    Foo foo1 = Foo(1, 2);
    Foo foo2 = Foo(2, 3);
};
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • Is this because the class instances are considered to be 'const' type objects? I had believed that only const members had to be initialized in constructor initialization list? – Wilsonator Apr 21 '13 at 22:08
  • 1
    @Wilsonator: No, this is the way you initialize sub-objects in general. `const` members (or reference members) can *only* be initialized this way (`const` members could be default-constructed though) – Andy Prowl Apr 21 '13 at 22:09
  • Just to be clear the copy-initialization syntax is also C++11? – Wilsonator Apr 21 '13 at 22:23
  • 1
    @Wilsonator: Yes, it is. In C++03 it is not allowed – Andy Prowl Apr 21 '13 at 22:25
5

You have to initialize those members through your constructor:

class Bar
{
    public:
        Foo foo1;
        Foo foo2;

        Bar() : foo1(1, 2), foo2(2, 3) {}
};

What follows the colon is the member-initializer list.

Community
  • 1
  • 1
David G
  • 94,763
  • 41
  • 167
  • 253
1

In C++03, Bar needs to initialize its attributes within its constructor:

class Bar
{
    public:
        Foo foo1;
        Foo foo2;

        Bar() : foo1(1,2), foo2(2,3) {} 
};
oHo
  • 51,447
  • 27
  • 165
  • 200