Usage of Initilizer list with default keyword - c++

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 {}.

Related

Practical difference between implicit and defaulted constructor in C++

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.

How to write a default constructor in c++?

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.

Is it true that a default constructor is synthesized for every class that does not define one?

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.

What is the concept of default constructor?

help me in getting the concept of default constructor with example.
i don't know when to use default constructor in the program and when not to.
help me coming over this problem.explain it with an example for me.
when it is necessary to use it?
#include<iostream>
using namespace std;
class abc
{
public:
abc()
{
cout<<"hello";
}
};
int main()
{
abc a;
system("pause");
return 0;
}
so actually what is the use of default constructor and when it is necessary to use it?
A class that conforms to the concept DefaultConstrutible allows the following expressions (paragraph 17.6.3.1 of N3242):
T u; // object is default initialized
T u{}: // object is value intialized
T(); T{}; // value initialized temporary
So much for the concept. Paragraph 12.1/5 actually tells us what a default constructor is
A default constructor for a class X is a constructor of class X that
can be called without an argument. If there is no user-declared
constructor for class X, a constructor having no parameters is
implicitly declared as defaulted (8.4). An implicitly-declared default
constructor is an inline public member of its class. ...
With the introduction of deleted special member functions, the standard also defines a list of cases where no implicit default constructor is available and the distinction of trivial and non-trivial default constructors.
If you don't need to do anything as your class is instantiated. Use the default constructor, any situation else you will have to use your own constructor as the default constructor basically does nothing.
You also don't need to write any "default" constructor.
class abc {
};
int main() {
abc a; //don't want to do anything on instatiation
system("pause");
return 0;
}
class abc {
private:
int a;
public:
abc(int x) { a = x };
}
int main() {
abc a(1); //setting x to 1 on instantiation
system("pause");
return 0;
}
Constructor is a special function, without return type. Its name must be as the class\struct name. It doesn't have an actual name as a function, as Kerrek-SB pointed out.
Default constructor is the one that has no parameters, or has parameters all with a default value.
Constructor function is being called only once - when an object is instantiated
Constructor is called through a new expression or an initialization expression. It cannot be called "manually".
Useful for initializing object's fields, usually with a member initializer list.
Check this.
Default constructor is constructor with no argument and will be called on these situations:
Instancing or newing an object of a class without any constructor, like:
abc a;
abc* aptr=new abc;
Declaring an array of a class, like:
abc a_array[10];
When you have a inherited class which does not call one of base class constructors
When you have a feature in your class from another class and you don't call a definite constructor of that feature's class.
When you use some containers of standard library such as vector, for example:
vector <abc> abc_list;
In these situations you have to have a default constructor, otherwise if you do not have any constructor, the compiler will make an implicit default constructor with no operation, and if you have some constructors the compiler will show you a compile error.
If you want to do one of the above things, use a default constructor to make sure every object is being instantiated correctly.

default constructors and object copying

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.