1

I was asked a question in my job interview:

"What is the difference between a struct and a class?"

and I simple replied:

"members of struct can be public only while members of a a class can be declared public or private."

but now I am little confused about my answer. I've been looking over the internet over a while for the difference between a strcut and a class but can not see this sort of difference anywhere. Was my answer to the employer incorrect?

If yes, what actually are the difference between struct and class in addition to this one:

members of a class are private by default, whereas members of a struct are public by default.

jogojapan
  • 68,383
  • 11
  • 101
  • 131
Ayse
  • 2,676
  • 10
  • 36
  • 61
  • In C++, there is no difference except for the one you already mentioned. Also, members of struct can be private also. – sgarizvi Jul 26 '13 at 04:58
  • In C++, they are the same thing. The only difference is the one you stated. – user123 Jul 26 '13 at 04:58
  • Please see this for the answer. http://stackoverflow.com/questions/1247745/default-visibility-of-c-class-struct-members – stev Jul 26 '13 at 05:00
  • From C++ perspective, the only difference is that, by default, struct members are "public", and class members are "private". C only has structs; no classes. In C, a struct contains only data. In C++, there is also space allocated for the "this" pointer. – paulsm4 Jul 26 '13 at 05:02
  • 1
    the ONLY part is wrong. Struct members aren't ONLY public (and vice versa). But other than that in C++ you are 100% correct. However in C and C# you are mistaken. C# treats structs as non-nullable objects (with some other changes as well but this is the main one). – Sellorio Jul 26 '13 at 05:03
  • @MrUniverse Without the ONLY, it would still be incomplete. – juanchopanza Jul 26 '13 at 05:06

1 Answers1

2

In C++, it is the last statement which is correct, but incomplete. By default, members of a class are private for a class, and are public for a struct.

What is missing is that the same applies to their base classes: inheritance is private by default in classes and public in structs. A struct and a class are equivalent in C++, and you can express exactly the same types using either keyword.

So it looks like your answer was incorrect.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480