Should the GameContext constructur
take a pointer to a World object
(World*), the address to a World
object (&World) or a reference to a
World object (World)?
First of all, the "address to a World
object" is the same thing as a pointer to a World
object. A pointer is a type of variable that stores an object's address. If you pass an address, then the parameter that corresponds to the address you passed will be a pointer.
Whether you want to take a pointer or not depends on the semantics of the World
class. If you take a value (and not a pointer), then you will receive a copy of the World object passed in. If something other than the GameContext
object needs to perform operations on that same world object, then you will want to pass in and store a pointer. If this is not necessary, or if the World
class operates internally such that all copies of a World
object use a common set of data, then you can pass by value.
What is the const keyword when used
near a parameter? For example:
GameContext(const World &world)
const
means "cannot be modified", just like it means anywhere else. A common idom in C++, as you have given in your example, is to take a constant reference instead of taking a value. When the parameter is an object (as opposed to a fundamental type like int
or bool
), this is more efficient than taking a value, since a copy is not made in this case. However the const
prevents the function from modifying the referenced parameter, so to the caller, it does not matter than it is a reference.