Reputation: 676
I have searched previous questions, and have not found a satisfying answer to my question:
If I define an empty default constructor for a class, as for example
class my_class{
public:
myclass(){}
private:
int a;
int* b;
std::vector<int> c;
}
my understanding is that if I define an object using the default constructor, say
my_class my_object;
then my_object.a will be a random value, the pointer my_object.b will also be a random value, however the vector c will be a well-behaved, empty vector.
In other words, the default constructor of c is called while the default constructors of a and b is not. Am I understanding this correctly? What is the reason for this?
Thank you!
Upvotes: 1
Views: 647
Reputation: 320381
a
and b
have non-class types, meaning that they have no constructors at all. Otherwise, your description is correct: my_object.a
and my_object.b
will have indeterminate values, while my_object.c
will be properly constructed.
As for why... by writing a user-defined constructor and not mentioning a
and b
in the initializer list (and not using C++11 in-class member initializers) you explicitly asked the compiler to leave these members uninitialized.
Note that if your class did not have a user-defined constructor, you'd be able to control the initial values of my_object.a
and my_object.b
from outside, by specifying initializers at the point of object declaration
my_class my_object1;
// Garbage in `my_object1.a` and `my_object1.b`
my_class my_object2{};
// Zero in `my_object2.a` and null pointer in `my_object2.b`
But when you wrote your own default constructor, you effectively told the compiler that you want to "override" this initialization behavior and do everything yourself.
Upvotes: 7
Reputation: 223699
Since a
and b
are not objects but primitive datatypes, there is no constructor to call. In contrast, c
is an object, so its default constructor is called.
Upvotes: 2