1

I want to initialize an array of class which contains a const member that must be initialize at construction.

#include <iostream>
class A
{
    private:
        const int var_;

    public:
        A(const int var) : var_(var){};

        int getVar(){return var_;}
};

class B
{
    private:
        A tab[2];

    public:
        B() : tab{2,5} {}; // The trick should be here, I think !

        int getA(int index) { return tab[index].getVar();}
};

int main(void)
{

    B b; // constraint : Dynamic allocation not allowed
    std::cout << b.getA(0) << std::endl;

    return 0;
}

This code does not compile because the constructor for class B is not right. Thanks for your help, Nicolas

nbout
  • 1,159
  • 8
  • 12

1 Answers1

0

The command

g++ -std=c++11 1.cpp

compiles the code above just fine. Running 1.exe prints 2 in the console.

P.S: g++.EXE (GCC) 4.9.0 20130616 (experimental)

Sergey K.
  • 24,894
  • 13
  • 106
  • 174