how to make const a non const string

Mar 9, 2009 at 12:43pm
Hello,

I have a listing where I declare a string path like this:

std::string basePath;

I would like to make this string also available to my other listings but as const, so I am using the following (in my other listings)

extern const std::string basePath;

but the linker complains that it can not find a const string named basepath because it was declared as non const.

Is there any way to overcome this problem?

Thank you very much for your time.
Mar 9, 2009 at 12:55pm
Why not just create a function that returns a copy of the string and hide the instantiation of the string?

in header file:

 
std::string getString();


in cpp file:

1
2
3
4
5
static std::string basePath;

std::string getString() {
   return basePath;
}
Mar 9, 2009 at 12:58pm
You could declare it const and later cast the const away. See:
http://www.cplusplus.com/doc/tutorial/typecasting.html

1
2
3
4
5
6
static const std::string basePath;
/*...*/

// cast the const-ness away to modify the string:
const_cast<std::string> basePath = "new base path" ;


But I would not recommend doing so. In most cases using casts is the wrong solution...
Last edited on Mar 9, 2009 at 12:59pm
Mar 9, 2009 at 1:03pm
jsmith thank you for your time.

I would like to know if there is a way to say the compiler to treat a variable as const from a certain point and bellow. Is this possible?

Thanks again.
Mar 9, 2009 at 1:09pm
Onur

When I try your solution I get:

error C2440: 'const_cast' : cannot convert from 'const std::string' to 'std::string'
Mar 9, 2009 at 2:37pm
I've found an even simpler solution without using casts:


1
2
std::string basePathInternal ("/dir1/dir2/");
static const std::string& basePathExternal = basePathInternal ;


You can modify basePath internally but externally it is read-only.

[EDIT]: Chose better names
Last edited on Mar 9, 2009 at 2:38pm
Mar 10, 2009 at 9:43am
Hello again,


Onur I will use your 'simpler' solution because it is clean and simple. Thank you very much.
Topic archived. No new replies allowed.