Default Constructor¶
Compiler Generated Default Constructor¶
Rule
A default constructor is automatically generated by the compiler when no user defined constructors are present in the class.
That constructor default-initializes all members.
#include <iostream>
#include <string>
#include <vector>
class Something
{
public:
std::string s;
std::vector<int> ints;
};
int main()
{
Something sth;
std::cout << "sth.s: \"" << sth.s << '"' << std::endl;
std::cout << "sth.ints.size(): " << sth.ints.size() << std::endl;
return 0;
}
$ ./code/c++03-default-ctor-compiler-generated
sth.s: ""
sth.ints.size(): 0
Compiler Generated Default Constructor: Pitfall: Built-In Types¶
Caution
Built-in datatypes (e.g. integers) are not initialized
This one reads uninitialized memory from the stack …
#include <iostream>
class Something
{
public:
int i;
};
void dirty_stack()
{
Something sth;
sth.i = 666;
(void)sth; // avoid "unused" warning
}
void use_uninitialized()
{
Something sth;
std::cout << "sth.i: " << sth.i << std::endl;
}
int main()
{
dirty_stack(); // <--- write 666 onto stack, AND LEAVE IT THERE
use_uninitialized(); // <--- TRAPPED!
return 0;
}
$ ./code/c++03-default-ctor-compiler-generated-pitfall
sth.i: 666
Solution: write default constructor manually!!
Manually Written Default Constructor¶
C++ pre 11
class Something
{
public:
Something() : i(0) {} // <--- explicit initialization
int i;
};
C++11 onwards
class Something
{
public:
int i{}; // <--- default value specified in member definition
};
What If User-Defined Constructors Are In Place?¶
No default constructor is generated
⟶ user has to supply one (if desired)
C++ pre 11
class Something
{
public:
Something() : i(0) {} // <--- user supplied default ctor
Something(int value) : i(value) {} // <--- user defined ctor
int i;
};
C++11 onwards
class Something
{
public:
Something() = default; // <--- force default ctor generation
Something(int value) : i(value) {} // <--- user defined ctor
int i{}; // <--- default value specified in member definition
};