-1

When do we need to use a structure in a pure C++ program? Is structure at all required in a pure C++ program? I understand that structure is the only way in a C program to encapsulate members and function pointers. But, if I use C++ to code my complete module, is it 100% alright if I stay away from structures and use a Class instead? Am I missing something?

(I googled but my question is very specific - is structure useless in pure C++ code)

=== EDITED === My question is not about the difference or commonalities between a structure and a class, but, do we need "struct" at all in C++, when you can 100% do away with a class. Is structure not redundant construct in C++, except for backward compatibility with C? I understand the difference between them w.r.t. the access specifiers but there are only syntactic differences.

Janakiram
  • 312
  • 1
  • 5
  • 12
  • 6
    your problem is not at all specific, google "c++ struct vs class" – thumbmunkeys Jan 30 '14 at 09:38
  • 2
    `struct` and `class` is essentialy the same thing, the difference is in the default access policy – Erbureth Jan 30 '14 at 09:39
  • @Janakiram Well this difference is exactly it: It's more convenient to have structs if you're not going to use any private methods or data fileds. (Plus the historic thing that structs originate from C). – stefan Jan 30 '14 at 09:49
  • If you understand the differences between struct and class, you know when and why to use and your question becomes irrelevant. – undu Jan 30 '14 at 09:49
  • @stefan, I feel, convenience is a personal choice. – Janakiram Jan 30 '14 at 09:52
  • 1
    @Janakiram Correct. Lot's of stuff in C++ is just for convenience. Theoretically we could achieve nearly everything in C, but who wants that? – stefan Jan 30 '14 at 09:53
  • @undu, I am not stuck with a problem or something like that, but was just thinking. I am kind of dry less experience in C++ and trying to figure out with your help, that we really don't need a "struct" (Just like, do, do-while and for - functionally all are same, only the syntax is different). – Janakiram Jan 30 '14 at 09:56
  • @Janakiram It is for backwards compatibility. It is rather unfortunate, because it causes a lot of confusion. I guess "class" sounded too cool to be left out back then, but perhaps they should have made `struct` and `class` perfect synonyms. – juanchopanza Jan 30 '14 at 09:58

1 Answers1

2

The struct has been kept in C++ for backward compatibility with C. By default the struct members are public but the class members are private. You can replace class and struct with each other and get the same result if the type of members are pre-defined.

user1436187
  • 3,252
  • 3
  • 26
  • 59