So I know that after you write a constructor in a class the default constructor goes away, so you have to start initializing every object. However, is there a way to write a default constructor so that you don't have to do this?
Thanks.
Before C++11
class MyClass
{
public:
MyClass(int x, int y) {}
MyClass() {}
};
or in C++11
class MyClass
{
public:
MyClass(int x, int y) {}
MyClass() = default;
};
You can write as many constructors as you like, but avoid making your class confusing to use.
The implicit default constructor goes away. You could still write another default constructor, one that doesn't take any arguments or that takes only args with default values; it's just not done for you by the compiler.
There's no reason you couldn't just write an empty constructor for a class A and take the default for each values. Perhaps not the best idea, but it can be done.
A() {/* empty */}
As noted in the comment if you're using c++11 you could also use the new default keyword to give you what the compiler would have if it did the "default"
A() = default;
class A
{
public:
// Or use A()=default for C++11
A(){}
A(int v):m_value(v){}
private:
int m_value;
};
int main()
{
A a; // Without default ctor ==>> error C2512: 'A' : no appropriate default constructor available
return 0;
}
struct S {
S(int) {} // non-default constructor that suppresses the implicit default constructor
S() = default; // bring the default constructor back
};
Note that there are two senses in which 'default' is used. There's a default constructor in the sense that it has a signature such that it will get used in "Default construction".
Secondly, there's 'default' in the sense that the implementation will match what the compiler automatically generates for an implicitly declared constructor.
You can make your class default constructible (default in the first sense) by giving your constructor default arguments.
struct S {
S(int = 10) {}
};
While = default is used to explicitly ask for a default implementation (default in the second sense).
Assuming your compiler implements = default using that is usually superior to doing S() {} for a number of reasons. = default in the class definition produces a non-user-provided constructor which has several effects.
user-provided special member functions are never trivial
a user-provided constructor disqualifies a type from being an aggregate.
value initialization includes zero-initialization for types with a non-user-provided default constructor
default initialization of const objects is disallowed for types without a user-provided default constructor
Occasionally one might want a user-provided function due to one of these effects. It's still possible to use = default by using it outside the class definition:
struct S {
S();
};
S::S() = default;
The above provides the compiler's default implementation but still counts as a user-provided default constructor. Additionally, this can be used to maintain ABI stability; at a later point = default can be replaced with another definition without necessarily requiring a recompile of all code constructing S objects, whereas it would be required with an inline defaulted default constructor.
Related
As far as I know, in C++ default constructors are declared (and defined if needed) implicitly if there is no user-defined default constructors. However, a user can declare a default constructor explicitly with the default keyword. In this post the answers are mainly about the difference between the implicit and default terms, but I didn't see an explanation about whether there is some difference between declaring a constructor as default and not declaring it at all.
As an example:
class Entity_default {
int x;
public:
Entity_default() = default;
}
class Entity_implicit {
int x;
}
In the example above, I declare a constructor for Entity_default as default and let the compiler declare a default constructor implicitly for Entity_implicit. I assume I do call these constructors later on. Is there any difference between these constructors in practice?
To the best of my knowledge, there is no functional or theoretical difference, both are still "trivial."
Uses of an explicit default constructors:
To ensure it exists when it would not otherwise be created, i.e. if a different constructor exists
You can default it in a different compilation unit:
Header file:
struct Foo
{
std::string bar;
Foo() noexcept;
~Foo();
};
Source file:
Foo::Foo() noexcept = default;
Foo::~Foo() = default;
Useful if you don't want an inline constructor to save code size or ensure ABI compatibility. Note that at this point, it is no longer a trivial object.
Why I cannot use default keyword after initialization list
class classA
{
int num;
public:
classA():num(3) = default;
};
Alternative solution:
class classA
{
int num = 3;
public:
classA() = default;
};
= default provides a definition of the constructor. Note that it doesn't provide the body, it provides a definition. The definition of a constructor includes both the mem-initialiser-list and the body. So if you want your own mem-initialiser-list, you must provide the entire definition yourself.
Also note that there is zero problem with doing that. Just write {} instead of = default. A default constructor defined with = default performs exactly the same operations as one defined with {}.
The only difference between these is that a constructor defined with = default right at its declaration is not considered user-provided and thus allows the class to be a trivial class. But since you want something non-trivial to happen in the constructor, you get exactly what you want by using {}.
I don't understand why would I ever do this:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Why not just say:
S() {} // instead of S() = default;
why bring in a new syntax for that?
A defaulted default constructor is specifically defined as being the same as a user-defined default constructor with no initialization list and an empty compound statement.
§12.1/6 [class.ctor] A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used to create an object of its class type or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer (12.6.2) and an empty compound-statement. [...]
However, while both constructors will behave the same, providing an empty implementation does affect some properties of the class. Giving a user-defined constructor, even though it does nothing, makes the type not an aggregate and also not trivial. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use = default.
§8.5.1/1 [dcl.init.aggr] An aggregate is an array or a class with no user-provided constructors, [and...]
§12.1/5 [class.ctor] A default constructor is trivial if it is not user-provided and [...]
§9/6 [class] A trivial class is a class that has a trivial default constructor and [...]
To demonstrate:
#include <type_traits>
struct X {
X() = default;
};
struct Y {
Y() { };
};
int main() {
static_assert(std::is_trivial<X>::value, "X should be trivial");
static_assert(std::is_pod<X>::value, "X should be POD");
static_assert(!std::is_trivial<Y>::value, "Y should not be trivial");
static_assert(!std::is_pod<Y>::value, "Y should not be POD");
}
Additionally, explicitly defaulting a constructor will make it constexpr if the implicit constructor would have been and will also give it the same exception specification that the implicit constructor would have had. In the case you've given, the implicit constructor would not have been constexpr (because it would leave a data member uninitialized) and it would also have an empty exception specification, so there is no difference. But yes, in the general case you could manually specify constexpr and the exception specification to match the implicit constructor.
Using = default does bring some uniformity, because it can also be used with copy/move constructors and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the = default (or = delete) syntax uniformly for each of these special member functions makes your code easier to read by explicitly stating your intent.
I have an example that will show the difference:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(){}
};
class B
{
public:
int x;
B()=default;
};
int main()
{
int x = 5;
new(&x)A(); // Call for empty constructor, which does nothing
cout << x << endl;
new(&x)B; // Call for default constructor
cout << x << endl;
new(&x)B(); // Call for default constructor + Value initialization
cout << x << endl;
return 0;
}
Output:
5
5
0
As we can see the call for empty A() constructor does not initialize the members, while B() does it.
n2210 provides some reasons:
The management of defaults has several problems:
Constructor definitions are coupled; declaring any constructor suppresses the default constructor.
The destructor default is inappropriate to polymorphic classes, requiring an explicit definition.
Once a default is suppressed, there is no means to resurrect it.
Default implementations are often more efficient than manually specified implementations.
Non-default implementations are non-trivial, which affects type semantics, e.g. makes a type non-POD.
There is no means to prohibit a special member function or global operator without declaring a (non-trivial) substitute.
type::type() = default;
type::type() { x = 3; }
In some cases, the class body can change without requiring a change in member function definition because the default changes with
declaration of additional members.
See Rule-of-Three becomes Rule-of-Five with C++11?:
Note that move constructor and move assignment operator won't be
generated for a class that explicitly declares any of the other
special member functions, that copy constructor and copy assignment
operator won't be generated for a class that explicitly declares a
move constructor or move assignment operator, and that a class with a
explicitly declared destructor and implicitly defined copy constructor
or implicitly defined copy assignment operator is considered
deprecated
It's a matter of semantics in some cases. It's not very obvious with default constructors, but it becomes obvious with other compiler-generated member functions.
For the default constructor, it would have been possible to make any default constructor with an empty body be considered a candidate for being a trivial constructor, same as using =default. After all, the old empty default constructors were legal C++.
struct S {
int a;
S() {} // legal C++
};
Whether or not the compiler understands this constructor to be trivial is irrelevant in most cases outside of optimizations (manual or compiler ones).
However, this attempt to treat empty function bodies as "default" breaks down entirely for other types of member functions. Consider the copy constructor:
struct S {
int a;
S() {}
S(const S&) {} // legal, but semantically wrong
};
In the above case, the copy constructor written with an empty body is now wrong. It's no longer actually copying anything. This is a very different set of semantics than the default copy constructor semantics. The desired behavior requires you to write some code:
struct S {
int a;
S() {}
S(const S& src) : a(src.a) {} // fixed
};
Even with this simple case, however, it's becoming much more of a burden for the compiler to verify that the copy constructor is identical to the one it would generate itself or for it to see that the copy constructor is trivial (equivalent to a memcpy, basically). The compiler would have to check each member initializer expression and ensure it's identical to the expression to access the source's corresponding member and nothing else, make sure no members are left with non-trivial default construction, etc. It's backwards in a way of the process the compiler would use to verify that it's own generated versions of this function is trivial.
Consider then the copy assignment operator which can get even hairier, especially in the non-trivial case. It's a ton of boiler-plate that you don't want to have to write for many classes but you're be forced to anyway in C++03:
struct T {
std::shared_ptr<int> b;
T(); // the usual definitions
T(const T&);
T& operator=(const T& src) {
if (this != &src) // not actually needed for this simple example
b = src.b; // non-trivial operation
return *this;
};
That is a simple case, but it's already more code than you would ever want to be forced to write for such a simple type as T (especially once we toss move operations into the mix). We can't rely on an empty body meaning "fill in the defaults" because the empty body is already perfectly valid and has a clear meaning. In fact, if the empty body were used to denote "fill in the defaults" then there'd be no way to explicitly make a no-op copy constructor or the like.
It's again a matter of consistency. The empty body means "do nothing" but for things like copy constructors you really don't want "do nothing" but rather "do all the things you'd normally do if not suppressed." Hence =default. It's necessary for overcoming suppressed compiler-generated member functions like copy/move constructors and assignment operators. It's then just "obvious" to make it work for the default constructor as well.
It might have been nice to make default constructor with empty bodies and trivial member/base constructors also be considered trivial just as they would have been with =default if only to make older code more optimal in some cases, but most low-level code relying on trivial default constructors for optimizations also relies on trivial copy constructors. If you're going to have to go and "fix" all your old copy constructors, it's really not much of a stretch to have to fix all your old default constructors, either. It's also much clearer and more obvious using an explicit =default to denote your intentions.
There are a few other things that compiler-generated member functions will do that you'd have to explicitly make changes to support, as well. Supporting constexpr for default constructors is one example. It's just easier mentally to use =default than having to mark up functions with all the other special keywords and such that are implied by =default and that was one of the themes of C++11: make the language easier. It's still got plenty of warts and back-compat compromises but it's clear that it's a big step forward from C++03 when it comes to ease-of-use.
Due to the deprecation of std::is_pod and its alternative std::is_trivial && std::is_standard_layout, the snippet from #JosephMansfield 's answer becomes:
#include <type_traits>
struct X {
X() = default;
};
struct Y {
Y() {}
};
int main() {
static_assert(std::is_trivial_v<X>, "X should be trivial");
static_assert(std::is_standard_layout_v<X>, "X should be standard layout");
static_assert(!std::is_trivial_v<Y>, "Y should not be trivial");
static_assert(std::is_standard_layout_v<Y>, "Y should be standard layout");
}
Note that the Y is still of standard layout.
There is a signicant difference when creating an object via new T(). In case of defaulted constructor aggregate initialization will take place, initializing all member values to default values. This will not happen in case of empty constructor. (won't happen with new T either)
Consider the following class:
struct T {
T() = default;
T(int x, int c) : s(c) {
for (int i = 0; i < s; i++) {
d[i] = x;
}
}
T(const T& o) {
s = o.s;
for (int i = 0; i < s; i++) {
d[i] = o.d[i];
}
}
void push(int x) { d[s++] = x; }
int pop() { return d[--s]; }
private:
int s = 0;
int d[1<<20];
};
new T() will initialize all members to zero, including the 4 MiB array (memset to 0 in case of gcc). This is obviously not desired in this case, defining an empty constructor T() {} would prevent that.
In fact I tripped on such case once, when CLion suggested to replace T() {} with T() = default. It resulted in significant performance drop and hours of debugging/benchmarking.
So I prefer to use an empty constructor after all, unless I really want to be able to use aggregate initialization.
If the class doesn't have the constructor, will the compiler make one default constructor for it ?
Programmers new to C++ often have two common misunderstandings:
That a default constructor is synthesized for every class that does
not define one
from the book Inside the C++ Object Model
I am at a loss...
This is well explained in the section from which this quote is taken. I will not paraphrase it in its entirety, but here is a short summary of the section content.
First of all, you need to understand the following terms: implicitly-declared, implicitly-defined, trivial, non-trivial and synthesized (a term that is used by Stanley Lippman, but is not used in the standard).
implicitly-declared
A constructor is implicitly-declared for a class if there is no user-declared constructor in this class. For example, this class struct T { }; does not declare any constructor, so the compiler implicitly declares a default constructor. On the other hand, this class struct T { T(int); }; declares a constructor, so the compiler will not declare an implicit default constructor. You will not be able to create an instance of T without parameters, unless you define your own default constructor.
implicitly-defined
An implicitly-declared constructor is implicitly-defined when it is used, i.e. when an instance is created without parameters. Assuming the following class struct T { };, the line T t; will trigger the definition of T::T(). Otherwise, you would have a linker error since the constructor would be declared but not defined. However, an implicitly-defined constructor does not necessarily have any code associated with it! A default constructor is synthesized (meaning that some code is created for it) by the compiler only under certain circumstances.
trivial constructor
An implicitly-declared default constructor is trivial when:
its class has no virtual functions and no virtual base classes and
its base classes have trivial constructors and
all its non-static members have trivial constructors.
In this case, the default compiler has nothing to do, so there is no code synthesized for it. For instance, in the following code
struct Trivial
{
int i;
char * pc;
};
int main()
{
Trivial t;
}
the construction of t does not involve any operations (you can see that by looking at the generated assembly: no constructor is called to construct t).
non-trivial
On the other hand, if the class does not meet the three requirements stated above, its implicitly-declared default constructor will be non-trivial, meaning that it will involve some operations that must be performed in order to respect the language semantics. In this case, the compiler will synthesize an implementation of the constructor performing these operations.
For instance, consider the following class:
struct NonTrivial
{
virtual void foo();
};
Since it has a virtual member function, its default constructor must set the virtual table pointer to the correct value (assuming the implementation use a virtual method table, of course).
Similarly, the constructor of this class
struct NonTrivial
{
std::string s;
};
must call the string default constructor, as it is not trivial. To perform these operations, the compiler generates the code for the default constructor, and calls it anytime you create an instance without parameters. You can check this by looking at the assembly corresponding to this instantiation NonTrivial n; (you should see a function call, unless the constructor has been inlined).
Summary
When you don't provide any constructor for your class, the compiler implicitly declares a default one. If you try to use it, the compiler implicitly defines it, if it can (it is not always possible, for instance when a class has a non-default-constructible member). However, this implicit definition does not imply the generation of any code. The compiler needs to generate code for the constructor (synthesize it) only if it is non-trivial, meaning that it involves certain operations needed to implement the language semantics.
N.B.
Stanley B Lippman's "Inside the C++ object model" and this answer deals with (a possible) implementation of C++, not its semantics. As a consequence, none of the above can be generalized to all compilers: as far as I know, an implementation is perfectly allowed to generate code even for a trivial constructor. From the C++ user point of view, all that matters is the "implicitly-declared/defined` aspect (and also the trivial/non-trivial distinction, as it has some implications (for instance, an object of a class with non-trivial constructor cannot be a member of a union)).
I think the misconception is:
That a default constructor is synthesized for every class that does not define one
That people think the default constructor, which accepts no arguments, will always be generated if you don't declare it yourself.
However, this is not true, because if you declare any constructor yourself, the default one will not be automatically created.
class MyClass {
public:
MyClass(int x) {}; // No default constructor will be generated now
};
This will lead to problems like when beginners expect to use MyClass like this:
MyClass mc;
Which won't work because there is no default constructor that accepts no args.
edit as OP is still a little confused.
Imagine that my MyClass above was this:
class MyClass {
};
int main() {
MyClass m;
}
That would compile, because the compiler will autogenerate the default constructor MyClass() because MyClass was used.
Now take a look at this:
#include <iostream>
class MyClass {
};
int main() {
std::cout << "exiting\n";
}
If this were the only code around, the compiler wouldn't even bother generating the default constructor, because MyClass is never used.
Now this:
#include <iostream>
class MyClass {
public:
MyClass(int x = 5) { _x = x; }
int _x;
};
int main() {
MyClass m;
std::cout << m._x;
}
The compiler doesn't generate default constructor MyClass(), because the class already has a constructor defined by me. This will work, and MyClass(int x = 5) works as your default constructor because it can accept no arguments, but it wasn't generated by the compiler.
And finally, where beginners might run into a problem:
class MyClass() {
public:
MyClass(int x) { _x = x; }
int _x;
};
int main() {
MyClass m;
}
The above will throw you an error during compilation, because MyClass m needs a default constructor (no arguments) to work, but you already declared a constructor that takes an int. The compiler will not generate a no-argument constructor in this situation either.
A default constructor is synthesized for every class that does not define one if:
The code using the class needs one & only if
There is no other constructor explicitly defined for the class by you.
All the upvoted answers thus far seem to say approximately the same thing:
A default constructor is synthesized for every class that does not have any user-defined constructor.
which is a modification of the statement in the question, which means
A default constructor is synthesized for every class that does not have a user-defined default constructor.
The difference is important, but the statement is still wrong.
A correct statement would be:
A default constructor is synthesized for every class that does not have any user-defined constructor and for which all sub-objects are default-constructible in the context of the class.
Here are some clear counter-examples to the first statement:
struct NoDefaultConstructor
{
NoDefaultConstructor(int);
};
class Surprise1
{
NoDefaultConstructor m;
} s1; // fails, no default constructor exists for Surprise1
class Surprise1 has no user-defined constructors, but no default constructor is synthesized.
It doesn't matter whether the subobject is a member or a base:
class Surprise2 : public NoDefaultConstructor
{
} s2; // fails, no default constructor exists for Surprise2
Even if all subobjects are default-constructible, the default constructor has to be accessible from the composite class:
class NonPublicConstructor
{
protected:
NonPublicConstructor();
};
class Surprise3
{
NonPublicConstructor m;
} s3; // fails, no default constructor exists for Surprise3
Yes a default constructor is always there by default if you don't define a constructor of your own (see the default constructor section here).
http://www.codeguru.com/forum/archive/index.php/t-257648.html
Quote:
The following sentense are got from the book "Inside the C++ object model" , written by Stanley B. Lippman.
There are four characteristics of a class under which the compiler
needs to synthesize a default constructor for classes that declare no
constructor at all. The Standard refers to these as implicit,
nontrivial default constructors. The synthesized constructor fulfills
only an implementation need. It does this by invoking member object or
base class default constructors or initializing the virtual function
or virtual base class mechanism for each object. Classes that do not
exhibit these characteristics and that declare no constructor at all
are said to have implicit, trivial default constructors. In practice,
these trivial default constructors are not synthesized. ...
Programmers new to C++ often have two common misunderstandings:
That a default constructor is synthesized for every class that does
not define one
That the compiler-synthesized default constructor provides explicit
default initializers for each data member declared within the class
As you have seen, neither of these is true.
I'm wondering why I need to declare a default constructor in this case. For one thing doesn't the compiler do that automatically if i leave it out? And regardless, I still don't see why its necessary. Also, I get the error even if I omit 'obj_B = origin.obj_B;'
class B
{
public:
bool theArray[5] ;
B(bool x) {theArray[1] = x;};
//B(){};
};
class A
{
public:
B obj_B;
A() : obj_B(1) {};
A(A const &origin) {obj_B = origin.obj_B;}; //error:no matching function for call
//to B::B()
};
int main ()
{
std::vector <A> someAs;
for(int q=0;q<10;q++)
someAs.push_back(A());
for(int q=0;q<10;q++)
std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
The compiler only creates a default constructor if you don't specify an alternate constructor.
Because you made:
B(bool x) {theArray[1] = x;}
The default constructor will not be created for you.
The specific error you're getting is because A(A const &origin) doesn't specify the constructor to use for obj_B explicitly.
The following code would work:
A(A const &origin) : obj_B(1) {obj_B = origin.obj_B;}
By the way, you don't need a trailing semicolon on a function definition.
If you don't define any ctors for a class, the compiler will synthesize a default constructor. If you define another constructor though (e.g., one that takes an argument) then the compiler does not synthesize one for you, and you have to define one yourself.
In case you care, C++ 0x adds an "=default;" declaration to tell the compiler to provide a ctor that it would have provided by default, even if you have defined another ctor.
To define a copy constructor for A that does not require a default constructor for B, use member initializer syntax:
class A {
public:
A(A const& origin) : obj_B(origin.obj_B) {}
//...
};
To make one final point...
Assuming you hadn't defined a non-default constructor, failing to define a default constructor would've resulted in the elements of theArray[] being undefined. That is a bad habit to get into usually leading to bugs down the road.