I’m learning C++. I have a simple class named GameContext:
class GameContext {
public:
GameContext(World world);
virtual ~GameContext();
};
To initialize a GameContext object, I need a World object.
-
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)? -
What is the
constkeyword when used near a parameter? For example:GameContext(const World &world)
Thanks.
First, teminology: You’re right that a
World *would be a pointer to a World object. AWorld &, however, would be a reference to a World object. AWorldwould be a copy of the World object, not a reference to it.The
const(used primarily with a pointer or reference, as inWorld const &worldorWorld const *world) means that you’re getting a reference/pointer to a const object — in other words, you’re not allowed to modify the original object to which it refers/points.For small objects, you usually want to pass a copy. For large objects, you’ll typically want to pass a const reference. There are exceptions to this, but that’s a reasonable rule of thumb to use until you’ve learned enough more to know when to break the rules (so to speak).
Just based on the name, I’d guess your World object is probably large enough that you probably want to pass it by const reference, so your ctor should look like: