Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accidentially 'instantiate' an abstract class type using brace-initializers? [duplicate]

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?

like image 853
djf Avatar asked Feb 03 '17 18:02

djf


1 Answers

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

like image 107
Christian Hackl Avatar answered Sep 29 '22 13:09

Christian Hackl