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
  • 82,182
  • 10
  • 99
  • 146
1

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

unwind
  • 378,987
  • 63
  • 458
  • 590
Matteo Italia
  • 119,648
  • 17
  • 200
  • 293
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
  • 33,740
  • 12
  • 54
  • 68
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