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.
Related
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.
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.
I think this impossible but I might as well ask.
Can I declare a private Copy-Constructor and still use the default implementation?
Background: I have a class with very big vectors and I do not want to call the copy constructor except for one member function. Using a standard public copy-ctor might
easily lead to bugs like e.g. forgetting a reference in an iteration (foreach(Type el,vectOfBigObjects) instead of foreach(Type const& el,vectOfBigObjects)). Hence I want to keep the standard copy consructor but just make it private.
Is this possible without rewriting the copy-ctors definition ?
Is this possible without rewriting the copy-ctors definition ?
In C++11, yes. You just have to declare the constructor and mark it as defaulted:
struct X
{
// ...
private:
X(X const&) = default;
};
This will define a copy constructor which would have the same definition as an implicitly generated one, but will be private. For instance:
struct X
{
X() { } // Required because a user-declared constructor in
// the definition of X inhibits the implicit generation
// of a default constructor (even if the definition is
// defaulted!)
void foo()
{
// ...
X tmp = *this; // OK!
// ...
}
private:
X(X const&) = default; // Default definition, accessible to
// member functions of X only!
};
int main()
{
X x;
// X x2 = x; // ERROR if uncommented!
}
Here is a live example.
Notice, that a user-declared constructor (including copy constructor) in a class definition inhibits the implicit generation of a default constructor, even if its definition is defaulted. This is why, for instance, I had to explicitly declare X's default constructor in the example above.
In my code I am doing the following, but I am not sure if I am "allowed" to or if it is a good designing technique. I need to create an empty constructor, but I also need a constructor that initializes the variables given the parameters. So I am doing the following:
This is the C.h file.
class C
{
private:
string A;
double B;
public:
//empty constructor
C();
C(string, double);
}
And my C.cpp file:
//this is how I declare the empty constructor
C::C()
{
}
C::C(string a, double b)
{
A = a;
B = b;
}
Is the way I am declaring the empty constructor right or do I need to set A= NULL and B=0.0?
Your empty constructor does not do what you want. The double data member will not be zero-initialized unless you do it yourself. The std::string will be initialized to an empty string. So the correct implementation of the default constructor would simply be
C::C() : B() {} // zero-initializes B
Concerning the other constructor, you should prefer the initialization list:
C::C(const string& a, double b) : A(a), B(b) {}
otherwise, what you are doing is an assignment to default constructed objects.
In C++11 and later you can use the following to generate a default no-param constructor:
C() = default;
This is neater than C(){}.
This doesn't initialize members. In C++11 you can initialize members in the same line of declaration:
int m_member = 0; // this is a class member
Those 2 features avoids having to create your own no param constructor to default initialize members. So your class can look like this when applying those 2 features:
class C
{
private:
string A;
double B = 0;
public:
C() = default;
C(string, double);
}
It is fine to do this and leave the constructor empty, but you should be aware that uninitialized fields have undefined value. string is a class and it's default constructor takes care of its initialization, but double is not initialized here (in your defualt constructor), and its value is undefined (it may be whatever value previously exists in the memory).
A is std::string, you can't set it to NULL but can set to empty string and std::string has default constructor which initialize it to empty string by default.
C::C()
:B(0.0)
{
}
Maybe you need a constructor constructor with default parameter instead of two constuctors?
C(const string& a= "", double b= 0.0)
: A(a),
B(b)
{
}
You are the only person who can answer this question, because it depends entirely on your requirements for a default-constructed object. Since you haven't mentioned what your requirements are, it's not possible to give a definitive answer. Some people will guess that you should initialize B to 0, but that decision should be based on your design, not on various notions of "good" programming practice.
You can leave it as is. You can do this because both string and double can be default constructed. Meaning that you can say string foo; and not get any errors.
Contrast this with what happens here:
class Bar{
private:
Bar(); //Explicitly private;
};
Bar b;
Here we get an error about no constructor Bar::Bar() being found.
As to whether it's a good idea: It's hard to say without knowing the situation this class will be used in. Perhaps it's perfectly sensible to have it be in a unconfigured position. But for many classes, such as a class representing a file for example, allowing a file object which doesn't point to any file is obviously wrong.
You are doing it correct and you can see it by compiling your code. Your default constructor will initialize the string and double by calling their default constructors. If you define any constructor in your class it will hide the default constructor created by compiler for you.
You can improve your constructor code by writing it like this
C::C(string a, double b):A(a), b(b)
{
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s the point in defaulting functions in C++11?
C++11 introduced defaulted methods (e.g. void myMethod() = default;).
What does it do to methods (how do methods behave after being defaulted). How do I use them properly (what are its uses)?
There are a number of class members that are considered "special member functions" by the C++ standard. These are:
The default constructor (a constructor that can be called with no parameters).
The copy constructor (a constructor that can be called with one parameter that is the object type as an lvalue reference).
The copy assignment operator (an operator= overload that can be called with one parameter that is the object type as either an lvalue reference or a value).
The move constructor (a constructor that can be called with one parameter that is the object type as an rvalue reference).
The move assignment operator (an operator= overload that can be called with one parameter that is the object type as either an rvalue reference or a value).
The destructor.
These member functions are special in that the language does special things with them on types. Another thing that makes them special is that the compiler can provide definitions for them if you do not. These are the only functions that you can use the = default; syntax on.
The issue is that the compiler will only provide a definition under certain conditions. That is, there are conditions under which a definition will not be provided.
I won't go over the entire list, but one example is what others have mentioned. If you provide a constructor for a type that is not a special constructor (ie: not one of the constructors mentioned above), a default constructor will not be automatically generated. Therefore, this type:
struct NoDefault
{
NoDefault(float f);
};
NoDefault cannot be default constructed. Therefore, it cannot be used in any context where default construction is needed. You can't do NoDefault() to create a temporary. You can't create arrays of NoDefault (since those are default constructed). You cannot create a std::vector<NoDefault> and call the sizing constructor without providing a value to copy from, or any other operation that requires that the type be DefaultConstructible.
However, you could do this:
struct UserDefault
{
UserDefault() {}
UserDefault(float f);
};
That would fix everything, right?
WRONG!
That is not the same thing as this:
struct StdDefault
{
StdDefault() = default;
StdDefault(float f);
};
Why? Because StdDefault is a trivial type. What does that mean? I won't explain the whole thing, but go here for the details. Making types trivial is often a useful feature to have, when you can do it.
One of the requirements of a trivial type is that it does not have a user-provided default constructor. UserDefault has a provided one, even though it does the exact same thing as the compiler-generated one would. Therefore, UserDefault is not trivial. StdDefault is a trivial type because = default syntax means that the compiler will generate it. So it's not user-provided.
The = default syntax tells the compiler, "generate this function anyway, even if you normally wouldn't." This is important to ensure that a class is a trivial type, since you cannot actually implement special members the way the compiler can. It allows you to force the compiler to generate the function even when it wouldn't.
This is very useful in many circumstances. For example:
class UniqueThing
{
public:
UniqueThing() : m_ptr(new SomeType()) {}
UniqueThing(const UniqueThing &ptr) : m_ptr(new SomeType(*ptr)) {}
UniqueThing &operator =(const UniqueThing &ptr)
{
m_ptr.reset(new SomeType(*ptr)); return *this;
}
private:
std::unique_ptr<SomeType> m_ptr;
};
We must write every one of these functions to make the class copy the contents of the unique_ptr; there's no way to avoid that. But we also want this to be moveable, and the move constructor/assignment operators won't automatically be generated for us. It'd silly to re-implement them (and error-prone if we add more members), so we can use the = default syntax:
class UniqueThing
{
public:
UniqueThing() : m_ptr(new SomeType()) {}
UniqueThing(const UniqueThing &ptr) : m_ptr(new SomeType(*ptr)) {}
UniqueThing(UniqueThing &&ptr) = default;
UniqueThing &operator =(const UniqueThing &ptr)
{
m_ptr.reset(new SomeType(*ptr)); return *this;
}
UniqueThing &operator =(UniqueThing &&ptr) = default;
private:
std::unique_ptr<SomeType> m_ptr;
};
Actually, default can only apply to special methods - i.e. constructors, destructors, assignment operator:
8.4.2 Explicitly-defaulted functions [dcl.fct.def.default]
1 A function definition of the form:
attribute-specifier-seqopt decl-specifier-seqopt declarator = default ;
is called an explicitly-defaulted definition. A function that is explicitly defaulted shall
— be a special member function,
— have the same declared function type (except for possibly differing ref-qualifiers and except that in
the case of a copy constructor or copy assignment operator, the parameter type may be “reference to
non-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,
and
— not have default arguments.
They behave the same as if the compiler generated them and are useful for cases like:
class Foo{
Foo(int) {}
};
here, the default constructor doesn't exist, so Foo f; wouldn't be valid. However, you can tell the compiler that you want a default constructor without the need to implement it yourself:
class Foo{
Foo() = default;
Foo(int) {}
};
EDIT: Pointed out by #Nicol Bolas in the comments, this truly doesn't explain why you'd prefer this over Foo() {}. What I'm guessing is: if you have a class w/ implementations separated in an implementation file, your class definition (if you don't use =default) would look like:
class Foo{
Foo();
Foo(int);
};
What I'm assuming is that the =default is meant to provide an idiomatic way of telling you "we're not doing anything special in the constructor". With the above class definition, the default constructor could very well not value-initialize the class members. With the =default you have that guarantee just by looking at the header.
Using = default on a constructor or copy-constructor means that the compiler will generate that function for you during compile-time. This happens normally when you exclude the respective functions from your class/struct. And in the case where you define your own constructor, this new syntax allows you to explicitly tell the compiler to default-construct the constructor where it normally won't. Take for instance:
struct S {
};
int main() {
S s1; // 1
S s2(s1); // 2
}
The compiler will generate both a copy-constructor and a default-constructor, thus allowing us to instantiate an S object like we did (1) and copy s2 into s1 (2). But if we define our own constructor, we find that we are unable to instantiate in the same way:
struct S {
S(int);
};
int main() {
S s; // illegal
S s(5); // legal
}
This fails because S has been given a custom-defined constructor, and the compiler won't generate the default one. But if we still want the compiler to give us one, we can explicitly convey this using default:
struct S {
S(int);
S() = default;
S(const S &) = default;
};
int main() {
S s; // legal
S s(5); // legal
S s2(s); // legal
}
Note, however, that only certain functions with certain function-signatures can be overloaded. It follows that this will fail because it is neither a copy-constructor nor a default-constructor or a move or assignment operator:
struct S {
S(int) = default; // error
};
We are also able to explicitly define the assignment operator (just like the default/copy-constructor, a default one is generated for us when we do not write out our own). So take for example:
struct S {
int operator=(int) {
// do our own stuff
}
};
int main() {
S s;
s = 4;
}
This compiles, but it won't work for us in the general case where we want to assign another S object into s. This is because since we wrote our own, the compiler doesn't provide one for us. This is where default comes into play:
struct S {
int operator=(int) {
// do our own stuff
}
S & operator=(const S &) = default;
};
int main() {
S s1, s2;
s1 = s2; // legal
}
But technically it's superfluous to define the assignment operator, copy, or move constructor as default when there is no other function "overriding" it as the compiler will provide one for you in that case anyway. The only case in which it won't provide you one is where you define your own one (or variation thereof). But as a matter of preference, asking the compiler to provide a default function using the new aforementioned syntax is more explicit and easier to see and understand if intentionally left out for the compiler.