Team 2550
Technical Documentation
|
|
The protection of certain members of a class is called encapsulation.
You have already seen some encapsulation in action. Remember the public
and private
designations in the Vector2d
class? Those are the primary means of encapsulation.
private
: The user does not have access to the data, they must interact with that data via methods.public
: The user has full access to both read and change the variable.Typically, you want to restrict direct variable access as much as possible. If encapsulation is not necessary, it is typically best to use a struct
. Let's compare a struct and class implementation of a type called ColorRGB
...
Problem statement: Implement an RGB color class or struct that will be fed into a multicolor LED light. The output on the computer can send unique sinals between 0 and 1023. Invalid output could damage the hardware.
class | struct |
---|---|
Can restrict access to the RGB values and make sure they are not out of bounds. | Can only store the information, the user is responsible for validating the data. |
Due to indirect access, methods can sometimes be slower than changing the values manually. | You don't always have to validate data. You only really need to validate the data when it is coming from an input with different bounds. |
Methods are very convenient and fast. | The equivalent of methods can be achieved by passing the struct into a function by reference, but this can be slower and is much less convenient. |
Default values can be initialized in the constructor. | There is no way to initialize the values besides setting each one individually. A constructor-like function can be created that returns an instance of the struct with default values set, but you have to run it manually. |
There can be a send method that outputs the color to the light. The new color could even be sent when the set method is run. | In this situation, a color is the only thing that will be output. |
In order to support multiple default values, there will have to be an additional value within the class that states the maximum value for any color. If you have an array with, say, 1000 objects, it will take a substantial amount of space. | Because the user will validate the value themselves, there is no need for the extra variable. |
For this particular application, it is difficult to know which to use. I would probably use a class in this case.
send()
method could be very useful, and it will be easier to read later on.As a rule of thumb, variables are usually private
and methods are public
.
In C++, there is no technical difference between a struct and class. There is only one slight behavioral difference. In a class, data not under an encapsulation label is automatically made private, whereas in a struct it is public.
struct
keyword came from C, which does not support methods.