16

Today I stumbled over the following issue. Someone got a little too fond of brace-initializers and accidentally tried to instantiate an interface class. Bear with me:

#include <iostream>

class IFoo
{
public:
   virtual ~IFoo() = default;
   virtual bool getFoo() const = 0;
};

void processFoo(const IFoo &fooImpl)
{
    bool foo = fooImpl.getFoo();
    std::cout << "got foo " << foo << std::endl;
}

int main()
{
   processFoo({});  // <- why is this valid?!
   return 0;
}

Until now I'd expected that the compiler would issue an error similar to the one you get when trying something silly like calling IFoo() or IFoo{}. However, the above code compiles without warning (on gcc 6.2) but will obviously terminate with 'pure virtual method called' as soon as you try to invoke the getFoo() method. Live example.

Could somebody kindly explain to me what is going on there?

greatwolf
  • 20,287
  • 13
  • 71
  • 105
djf
  • 6,592
  • 6
  • 44
  • 62
  • 3
    Looks like this is a g++ defect. – R Sahu Feb 03 '17 at 18:59
  • 2
    gcc 5.1 compiles a simplified main `int main() { const IFoo& foo = {}; return 0; } ` sorry can't format comments. ... also `const IFoo& foo{}; ` compiles – Richard Critten Feb 03 '17 at 19:06
  • @djf it looks like clang 5.0.0 HEAD properly catches this error from testing on [melpon's online compiler](http://melpon.org/wandbox/). – greatwolf Feb 03 '17 at 23:02

1 Answers1

5

It's a known GCC bug. Unfortunately, the issue is still open and not assigned to anyone, it seems.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • They must be waiting for the standard to adopt some kind of default instantiation and Scala evidences to proclaim it a feature. – bipll Feb 03 '17 at 22:06
  • Thanks for digging up that link, Christian. I've been looking for known issues, but couldn't find anything pertinent : ) – djf Feb 04 '17 at 09:38