C++ structures and constructors
A quick question about structures in C++ that I haven't managed to find the answer for:
I've read that the only difference between structures and classes is the member-visibility. So, does the compiler give the structure a default constructor? (and a default copyconstructor, destructor, and assignment operator aswell?) And can you d开发者_运维问答efine all of the above yourself?
Thanks, István
Yes, it does, and yes, you can.
Yes to all your questions. The same holds true for classes.
I've read that the only difference between structures and classes is the member-visibility.
Thats correct. Just to note that this includes inherited classes:
struct S1 { int m1; };
struct S2: S1 { int m2; };
In S2, both m2 and m1 have public visibility. And an S2*
can be substituted where an S1*
is expected.
In C++ the only difference between a class
and a struct
is that class-members are private by default, while struct
-members default to public. So structures can have constructors, and the syntax is the same as for classes. But only if you do not have your structure in a union.
e.g.
struct TestStruct {
int id;
TestStruct() : id(42)
{
}
};
Credit goes to the answers in this question.
精彩评论