I was given a programming exercise by this e-book I'm currently learning C++ through. I came across something I find kind of odd, as it wants me to use a pointer-to-string in the function, but it also wants said string to have a default value. Now this makes no sense in my head as I thought pointers pointed to a memory location(Example: a variable's memory address.) But that makes no sense if isn't initialized.
One way I thought I could do this was to use the new keyword to create a new string object containing this default value, but I imagine this'd be pretty messy.
Basically the question is: Is there any other way I can go about this other than using new?
Basically the question is: Is there any other way I can go about this other than using new?
The answer is: It depends on who deletes the object.
Line 12 will create a memory leak if you use the default parameter. So I would expect that setCndBar(...) call delete when it doesn't need the string anymore.
If you knew that there is no delete you could provide the parameter like so:
1 2 3 4 5
...
string name = "test";
setCndBar(cndBar, &name); // Note the &
Apart from that: setCndBar(...) looks rather like a constructor.
I came across something I find kind of odd, as it wants me to use a pointer-to-string in the function, but it also wants said string to have a default value.
That is odd because the string class uses new internally to construct it, unless there is small string optimization.
in C++ prefer value semantics, references over pointers to STL objects, and especially avoid new wherever you can.
Btw the cal member should be unsigned, as good as negative calories sound I don't think it will happen !