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
.
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.
In a C++ structure type, the default access modifier for class member and member functions is "public".
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.
The default access modifiers for classes is internal and their constructors is 'private'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With