how to make const a non const string

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.
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;
}
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
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.
Onur

When I try your solution I get:

error C2440: 'const_cast' : cannot convert from 'const std::string' to 'std::string'
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
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.