0

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?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@basak you'll be surprised.... But BStats stats(); does not call any constructor, it does not even declare an object of type BStats but rather declares a function that takes no arguments and returns a BStats... Google for most-vexing-parse
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.