5

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

István Kohn
  • 135
  • 8

4 Answers4

11

Yes, it does, and yes, you can.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
1

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

unwind
  • 391,730
  • 64
  • 469
  • 606
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71
0

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.

Community
  • 1
  • 1