What's the point of a struct? I mean, isn't it basically the same thing as a class? So what it's used for?

Recommended Answers

All 8 Replies

Yeah, it is basically the same thing as a class. Keeping 'struct' in the language kept C++ a near-superset of C, since C contained structs. The real mystery to me is why they added 'class' in the first place. I guess it was to make the language seem more object-oriented.

Thanks guys. So the only difference is that members of a struct are public, and members of a class are private...

>So the only difference is that members of a struct are public, and members of a class are private...
Inheritance defaults to private for classes and public for structures too. Just remember that the default access for classes is private and for structures it's public.

Thanks. I have one more question:

In one of my books it was demonstrating a base class a derived class. In the base class the members were made protected....why would you do something like that? I know that when you have protected access it gives the derived class access to it, but doesn't this break OO style? Shouldn't those members of the base class be private but have accessors and mutator methods?

protected data members are virtually a no-no. what normally goes into the protected section are member functions, especially virtuals which may need to be called from derived classes but not necessarily the outside world.

>I know that when you have protected access it gives the derived
>class access to it, but doesn't this break OO style?
By members I assume you mean data members and not member functions. Protected access is a sneaky beast, because if you have protected data members then someone only has to derive from your class to legally access the internals. A lot of people (including me) believe that this is a travesty and anyone who attempts it should be shunned and ridiculed. Protected member functions are just fine though.

The guidelines for safe inheritance are simple:

1) All data is private
2) The public interface is for everyone
3) The protected interface is for derived classes
4) Prefer abstract base classes
5) Inheritance hierarchies should be broad and flat, not thin and deep

That covers your ass when it comes to access and it helps avoid annoying inheritance issues.

Thanks ;)
I believe I'm getting somewhere now, just got to get all these weird questions answered!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.