Default argument for pointer-to-string

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

struct CandyBar
{
	string brName;
	double weight;
	int cal;
};

void setCndBar(CandyBar &, string * = new string("Millennium Munch"), double = 2.85, int = 350);

int main()
{

    return 0;
}

void setCndBar(CandyBar & cndBar, string * name, double w, int c)
{

}
Last edited on
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.
The function will call delete on the pointer yes, so then I guess this solution isn't really a problem?

Also, I guess setCndBar() is a constructor, I'm just not used to the terms yet I guess :)
1
2
3
4
5
6
struct CandyBar
{
	string brName {"Millennium Munch"};
	double weight {2.85};
	int cal {350};
};


The above is the same as if you had a constructor with those default values and direct initialization.

The function will call delete on the pointer yes, so then I guess this solution isn't really a problem?
Then you need new when you pass the name:

1
2
3
...
setCndBar(cndBar, new string("test"));
...
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 !
coder777: Yeah, I just noticed that, just crashed the program cause I didn't include new.

TheIdeasMan: Thanks, that is some useful information, and cal probably should be insigned yes haha
Registered users can post here. Sign in or register to post.