1

I'm trying to pass two arguments to a constructor:

class CTest1
{
public:
    CTest1(const int i8BitImageID, const int i256BitImageID) : m_i8BitImageID(i8BitImageID), m_i256BitImageID(i256BitImageID) {};
private:
    int m_i8BitImageID;
    int m_i256BitImageID;
};

#define BITMAP_1_ID 1
#define BITMAP_2_ID 2

class CTest2
{
public:
    CTest1 test1(BITMAP_1_ID, BITMAP_2_ID); // Compile error here
};

When I compile this (using Visual Studio 2017), the line where I declare "test1" results in a "C2059: syntax error: 'constant'" error. I've tried with an without "const" in the definition of the constructor.

Thanks!

Steve A
  • 1,798
  • 4
  • 16
  • 34
  • 1
    Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius May 09 '18 at 15:28
  • Unfortunately, the compiler error is quite misleading this time. – user202729 May 09 '18 at 15:31
  • Possible duplicate of [VC++6 error C2059: syntax error : 'constant'](https://stackoverflow.com/questions/4519035/vc6-error-c2059-syntax-error-constant) – user202729 May 09 '18 at 15:34
  • 2
    Compiler sees this as function declaration of name `test1` that returns `CTest1` and does not accept constants there. Hense the error. @songyuanyao already explained how to fix it – Slava May 09 '18 at 15:34

1 Answers1

4

Default member initializer only works with brace or equals initializer. e.g.

class CTest2
{
public:
    CTest1 test1 = CTest1(BITMAP_1_ID, BITMAP_2_ID);
    CTest1 test2 {BITMAP_1_ID, BITMAP_2_ID};
};

Or you could use member initializer list.

class CTest2
{
public:
    CTest2() : test1(BITMAP_1_ID, BITMAP_2_ID) {}
    CTest1 test1;
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405