-3

I am able to do anything with structure that I can do with classes.give the exact situation that I cant use structures and have to use only classes

venkatesh
  • 9
  • 1

4 Answers4

4

That’s correct, they are strictly redundant. The reason for the existence of both classes and structs is purely historical.

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
  • "purely historical" makes it sound like things would definitely be done differently if starting afresh, which is not necessarily the case at all - I bet a lot of C++ programmers like having both available. While there's no particular functional need for both, there's some benefit in code concision, and arguably in implications that the choice might carry within a specific code base (though that's not necessarily a good practice). – Tony Delroy Apr 07 '14 at 10:06
  • @TonyD It’s hard to argue about something else’s internal state of mind. That said, yes, I do think that this would definitely be done differently today (and we can see this in other attempts at doing something similar to C++, such as D, Go and Rust). – Konrad Rudolph Apr 07 '14 at 10:21
4

There are two different constructs: struct and class, in a class, members are private by default, whereas in struct, members are public by default. That's all. They can be used either way according to convenience.

Dr. Debasish Jana
  • 6,865
  • 4
  • 27
  • 60
  • There's also nasty compiler mode where it moans and groans if you forward declare a class and it turns out to be a struct. Not all compiler do it though. – berkus Apr 07 '14 at 09:39
  • Not just "members are private" - bases too. @berkus: which is just one of the reasons for client code not to forward declare library content... the library should provide a forward declaration header if useful (e.g. ``) – Tony Delroy Apr 07 '14 at 09:50
  • @TonyD It also works the same if you forward declare a class in YOUR OWN library. Bases access is specified after the colon, default one would differ, but you can override. – berkus Apr 07 '14 at 11:49
2

In Short:

only difference between class and struct in c++ is that structs have default public members and bases and classes have default private members and bases.

Both can use inheritance

EmptyData
  • 2,294
  • 2
  • 23
  • 39
1

There is no such case. Structures are classes where members are public by default.

user2672165
  • 2,910
  • 17
  • 26