Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private and default constructor in C++11 and gcc

Code:

struct A
{
    private:
    A() = default; // Version 1.
};
struct B : public A
{};

struct C
{
    private:
    C() {}; // Version 2.
};
struct D : public C
{};

int main()
{
   B b;  // Compiles          under g++ 4.7.2
   D d;  // Compilation error under g++ 4.7.2
}

And two situations (with gcc 4.7.2):

  • If I compile this code (with the Version 1 of the A's constructor), there aren't problems.
  • If I use the second constructor, gcc says me that D::D() is private.

Question: if I use default constructors, why do problems dissapear? If A has private constructors, other classes can never create instances of A, not even its derivated classes, irrespective of the "defaultness" of its constructor's implementation.

like image 572
Peregring-lk Avatar asked Feb 22 '13 17:02

Peregring-lk


1 Answers

This smells like a GCC bug to me.

Neither the whole Clause 11 about member access control nor Section 8.4.2 about defaulted constructors mention anything about overriding the level of accessibility of defaulted constructors.

Besides, this code does not compile on Clang 3.2 and Intel ICC 13.0.

On the other hand, if you comment line X, the following line will not do what you think:

B b(); // This will declare a function that accepts no argument
       // and returns a value of type B

If you remove the parentheses, you should see the problem popping up:

B b; // ERROR: Constructor of A is private

However, GCC 4.7.2 (incorrectly) raises no compilation error. It also seems this hasn't been fixed in the beta version of GCC 4.8.0 (as of build 20130127).

like image 151
Andy Prowl Avatar answered Sep 29 '22 10:09

Andy Prowl