When passing non-const passed values from one overloaded method to the other causes a segfault but once they were changed to const it worked fine... curious as to how that worked?
void Button::setCaption( constchar * cstr ) {
string button_text = cstr; // showing string type for info purposes.
RenderText( button_text );
}
void Button::setCaption( const string &str ) {
setCaption( str.c_str() ); // Works fine!
}
Note: void Button::setCaption( const string str ) and void Button::setCaption( const string &str ) worked. However passing it by reference would probably be the best method. Any additional improvements would be appreciated.
The first approach causes a problem because setCaption(string) enters an infinite recursion when called. You see, str.c_str() returns a constchar *, so setCaption(str.c_str());doesn't call setCaption(char *). Instead, a temporary string object is created (because a string object can be created from a constchar * object), and setCaption(string) is called again. And then again... And then again... And there you have your seg-fault :P
Once you add the const keyword the problem is solved because now setCaption(str.c_str()); calls setCaption(constchar *) as you want it.
How would I stop str.c_str() from creating a temporary string object without using const? Create a temporary string variable inside the function, assign the value and then pass that variable?
You could do it by creating a temporary C string and use strcpy to copy str.c_str().
That would be a rather stupid way to do it, though. Changing setCaption to accept const char* instead is the correct way.
How would I stop str.c_str() from creating a temporary string object without using const?
You're basically asking this: "How do I solve this problem without solving the problem?"
Using const is the proper solution here. setCaption(constchar* cstr) is the way this function should be formed.
Any solution that doesn't involve const (like Athar's suggestion of creating a temporary buffer) will work, but will be hackish, error prone, and yield worse performance.
Just be const correct. It's the easiest solution here.
It was more of a information question =). I try to be const correct at first when possible. Other times I get the code to work first, then convert it over to const correctness afterwards.
I would strongly recommend that you get into the habit of writing const correct code
from the beginning. Const correctness is not something that is necessarily easy to
introduce later.