I’m creating a Class.
This class stores user preferences in a Struct.
When creating an instance of the class, I want the client to have the option of creating an instance with no preferences passed in or with a preferences struct passed in.
I can do this with pointers, but I wanted to know how I could do it by passing the preferences struct into the class by reference.
Either way, once the class receives the preferences it makes a copy for its own use.
Here’s what it looks like with pointers
struct preferences {};
class Useful
{
public:
Useful(preferences const * = NULL);
...
}
...
int main()
{
preferences * testPrefs;
...
Useful testClass(testPrefs);
// or if no prefs: Useful testClass;
...
}
So how would you pass the preferences struct in by reference when creating an instance of the class with a default value of no struct passed in? This is the line I’m stuck on, since neither NULL nor *NULL will work:
class Useful
{
public:
Useful(preferences & = ???????);
You point out the advantage of pointers over references, and how well pointers fit your situation, then announce you don’t want to use them.
You can still get what you want. Write two overloads for your constructor. One takes a reference, the other takes no parameters and does what the other constructor did when it got a null pointer.