2

Let's suppose I have the following code:

class A
{
    public:
        A(int Val)
        {
            _val = Val;
        }
        virtual ~A() = default;

    private:
        int _val = 0;
};

class B
{
    public:
        B() = default;
        virtual ~B() = default;

    private:
        A _a(3); // Error: expected identifier before numeric constant
};

int main()
{
    B b;
    return 0;
}

when I try to direct-initialize "A _a(3);" I will get the following error from the compiler: "xpected identifier before numeric constant" What is wrong about it?

Many thanks in advance

SomeDever
  • 57
  • 3
  • `A _a(3);` problem is that this looks like declaration of method, but instead a type value is used. – Marek R Aug 18 '18 at 10:18
  • Follow reading _"Most Vexing Parse"_ nearest SO link I can find (not an exact duplicate): https://stackoverflow.com/questions/1424510/most-vexing-parse-why-doesnt-a-a-work – Richard Critten Aug 18 '18 at 10:25

2 Answers2

4

You might use {} syntax:

class B
{
public:
    B() = default;
    virtual ~B() = default;

private:
    A _a{ 3 };
};

or use =:

class B
{
public:
    B() = default;
    virtual ~B() = default;

private:
    A _a = A(3);
};

parenthesis is not allowed to avoid vexing parse.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
3
A _a(3); 

C++ compiler interprets above line as a function _a() which returns a type A.

As pointed out by @Jarod42 A _a{3}; will work fine.

gov
  • 75
  • 1
  • 7