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.
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;
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.
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.
= dafault....defaultdafaultdid I just read?!?