István Kohn
István Kohn

Reputation: 135

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 define all of the above yourself?

Thanks, István

Upvotes: 5

Views: 588

Answers (4)

quamrana
quamrana

Reputation: 39404

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.

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126877

Yes to all your questions. The same holds true for classes.

Upvotes: 1

user195488
user195488

Reputation:

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.

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86459

Yes, it does, and yes, you can.

Upvotes: 11

Related Questions