4

Take the following sample code:

class Foo {
public:
    Foo(int x) {}
};

class Bar {
public:
    Bar(const Foo &foo1, const Foo &foo2) {}
};

void barfunc(const Bar &bar) {}

void func()
{
    int x = 1, y = 2;
    Bar bar(Foo(x), Foo(y));
    barfunc(bar);
}

The compiler complains:

test.cpp:17:16: error: invalid initialization of reference of type ‘const Bar&’ from expression of type ‘Bar(Foo, Foo)’
     barfunc(bar);
                ^
test.cpp:11:6: note: in passing argument 1 of ‘void barfunc(const Bar&)’
 void barfunc(const Bar &bar) {}
      ^~~~~~~

It seems that it has mistaken Bar bar(Foo(x), Foo(y)); for a function declaration. The tooltip in Visual Studio when I hover over bar gives me its type as Bar bar(Foo x, Foo y) rather than the intended Bar bar. This seems odd to me since I never knew a function declaration can have parentheses around the parameter names.

Doing either of the following fixes the issue:

    Bar bar = Bar(Foo(x), Foo(y));

or

    Bar bar((Foo)Foo(x), (Foo)Foo(y)); // though really only one cast is enough

But I'm wondering if there is a better more conventional way to fix it?

balki
  • 26,394
  • 30
  • 105
  • 151
Matt
  • 21,026
  • 18
  • 63
  • 115

0 Answers0