简体   繁体   中英

Quick C++ class confusion: What does this line mean?

I'm porting some C++ to Java, and encountered the following shorthand..but have no idea what this means or even how to go about Googling for it:

class mailbox {
public:
 mailbox(): sent(0),received(0),msg(0) { }

I don't understand what the method calls(?) after mailbox() signify.

Thanks.

This is member initialization syntax. It initializes the data members to the value specified before the body of the constructor begins.

It is the only way prior to C++11 to initialize a non-static constant data member, and is faster than initializing in the constructor's body.

It's like

mailbox() {
    sent = 0;
    received = 0;
    msg = 0;
}

except faster, and it can perform on const members as well. In fact, although it doesn't offer the ability to perform checking on the data member, you can still make use of it:

mailbox (Foo sent, Bar received, Foobar msg) : sent (0), received (0), msg (0) { //default values
    if (!setSent (sent)) 
        cout << "Error setting sent; sent is 0 instead."; //since we initialized it to 0 before
    //likewise for other members...
}

Assuming sent, received and msg are int, it is equivalent to:

mailbox() {
    sent = 0;
    received = 0;
    msg = 0;
}

This syntax exists because, unlike Java where all objects are pointers, in C++ you can have member variables that it's type does not have a default constructor. For exemple:

class Foo {
public:
    Foo(int x);
};

class Bar {
public:
    Bar(int x) { // ERROR, Foo does not have a default constructor
        foo = Foo(x);
    }

    Bar() : Foo(0) {} // OK, using Foo(int) instead of Foo()

private:
    Foo foo;
};

Note that in the example, even if Foo had a default constructor, Bar(int) would construct Foo twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM