Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiation of an abstract class via initializer list [duplicate]

Tags:

I would like to understand why the compiler allows the following code to compile

#include <iostream>  struct A {     A()     {         std::cout << "A::A\n";     }      virtual void f() const = 0; };  void g(const A& a) {     a.f(); }  int main() {     g({}); } 

It even outputs A::A when run.

If I replace g({}) with g(A()) it obviously doesn't compile. It complains that A is abstract and cannot be instantiated. Both Clang and GCC compile this fine without any warnings. When run both versions print pure virtual method called and terminate.

like image 946
detunized Avatar asked Sep 08 '16 13:09

detunized


1 Answers

This looks like a known g++ bug number 70939:

creating object of abstract class allowed in all versions of g++

g++ compiles ill formed C++ program successfully

class A { public:     A() {         printf("A()\n");     }     virtual void b() const = 0; }; int main() {     const A& a{};     a.b();     return 0; } 

Your code does the same thing as this line

const A& a{} 

as part of g({}) invocation.

like image 126
Sergey Kalinichenko Avatar answered Sep 27 '22 20:09

Sergey Kalinichenko