Reputation: 1929
I'm trying to understand what the following line does:
BStats stats = BStats();
The struct is defined as follows:
struct BStats
{
unsigned a;
unsigned b;
BStats& operator+=(const BStats& rhs)
{
this->a += rhs.a;
this->b += rhs.b;
return *this;
}
};
But I have no idea about what this line does. Is it calling the default constructor?
Upvotes: 0
Views: 544
Reputation: 208333
The expression BStats()
is described in the standard in 5.2.3/2:
The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized.
That is, the expression creates an rvalue of Bstats
type that is value-initialized. In your particular case, value-initialization means that the two members of the BStats
struct will be set to zero.
Note that this is different than the behavior of calling the default-constructor that is mentioned in other answers, as the default constructor will not guarantee that the members are set to 0.
Upvotes: 3
Reputation: 808
In C++ Classes and Structs are almost the same (the difference is that C++ structs are classes with public as the default attribute where a class's is private) so it's like calling a constructor.
Upvotes: 0
Reputation: 4954
Just like any class, a struct has a default constructor automatically created by the compiler. In your case, BStats() simply calls the default constructor, although the explicit call is useless.
Upvotes: 0