Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

=default ignores access specifier?

I found it quite odd that the following program still compiled fine despite the default constructor being private (4.8.1 g++):

 class A{
 private:
     A() = default;
     A(const A&) = default;
 };

 int main(){

     A a;

 }

Actually from 8.4.2[2] of the standard (N3242)

An explicitly-defaulted function may be declared constexpr only if it would have been implicitly declared as constexpr. If it is explicitly defaulted on its first declaration,

— it shall be public,

..........

What exactly is the purpose for the default specifier to ignore the access specification? I feel like that could cause an interface issue unwarranted by the class designer that didn't want users to create default values but needed the default constructor in the implementation. I thought that maybe it's because the default constructor is normally public and so the default aims to replicate it - but that doesn't answer why =default on the copy constructor doesn't ignore the private specification.

 class A{
 private:
     A() = default;
     A(const A&) = default;
 };

 int main(){

     A a;
     A b(a); //error: constexpr A::A(const A&) is private

 }

Actually I can't see from the standard where it mentions that explicitly-defaulted copy/move constructors/assignments aren't made public.

like image 352
Silversonic Avatar asked Oct 16 '15 21:10

Silversonic


People also ask

Which is the default access specifier?

The default access modifier is also called package-private, which means that all members are visible within the same package but aren't accessible from other packages: package com.

Which is the default access specifier in C++?

In a C++ structure type, the default access modifier for class member and member functions is "public".

Is default access specifier in Java if no specifier is used?

Easiest explanation - Default access is used if the programmer doesn't specify the specifier. This acts in a similar way as that of private. But since nothing is specified we call it to default access.

What is default access specifier of class in assembly?

The default access modifiers for classes is internal and their constructors is 'private'.


1 Answers

This is a gcc bug. Bug 57913 contains an example almost identical to yours. Bug 56429 contains links to several related bug reports, of which bug 54812 has been fixed in gcc 4.9, which indeed rejects your code.

error: 'constexpr A::A()' is private

Live demo

like image 83
Praetorian Avatar answered Oct 08 '22 12:10

Praetorian