struct or class
i am getting the hang of the syntax for structures and classes but i am confused about when to use each.
i have read that
a struct is used when only data is involved - seems a little weak.
a class is used when both data and functions are required.
i would ask for a suggestion on a good book but i have read differing acounts in different books with no concrete rule.
maybe some of you folks that do this for real could tell me how they are used in the industry.
It's up to you as they can both do the same thing, but a common practice is to use a struct when all your data/functions are to be public else use a class.
class=private(unless declared otherwise)
for your information
To start off, it is good to realize that any structure can be converted into a class and vice versa is always true as well.
The key difference between a structure and class is that the default access specification (i.e. public, protected, or private) is public when defining structures and private when defining classes.
Traditionally, a structure is used to organize more simple data types and simplify operations on them. For example, if you wanted to create a container for an x any y position, you would want to use a struct. This would help enclose the x and y values into a more logical point value. Therefore the data is more well contained than when it was previously disjoint as two pieces of information. As I mentioned, structures are also used to simplify operations between data. For instance, if I created a structure to contain a complex number (consisting of a real and imaginary double), I would want the ability to multiply, divide, add, and subtract complex numbers together. In a structure, the most valuable part is the data itself. That is way the default specification is public.
A class, on the other hand, is a little more abstract. A class is used to encapsulate an entire concept or object. The object that the class defines is usually supposed to be very independent (black boxing). Maybe the best way to explain it is through an example. If you wanted to encapsulate the use of a television, what data types would you specify? Well, it isn't really as obvious as the complex number or point data type. But we do know what a television should be able to do. Turn on. Turn off. Change channels. Adjust brightness, etc. Perhaps we can define a data type that maintans its state (memory) internally but is interfaced primarly through simpler functions like TurnOn(), TurnOff(), etc. This is why classes start off with a default private specification.
Neither is better than the other. It all depends on what the goal of container really is and what the most valuable part of the object really is (data or interface?).