Question:
C++ const char* or const string class declaration?
Fred
2011-07-15 23:32:24 UTC
Hi,

Basically, I have a class with a whole bunch of constant string literals that I need to declare. Since I can only declare const integral values in a class (where the prototypes go), I'm not sure where I should declare the strings. They can either be const std::string or const char*, I don't really care.

I know I can do something like this in my class.
const char* example() {return "123";};
However, this doesn't seem very good.

They way I have them now, they are declared as global constants.

Anyone know what I should do?

Thanks.
Three answers:
peteams
2011-07-16 03:11:11 UTC
You can't initialise the string constant in the class, as you correctly say.



If you want a constant string you need to do it in two steps, with a declaration:



class MyClass

{

static const char m_pszConstant[];

};



Followed in by definition:



const char MyClass::m_pszConstant[] = "Hello World";



That said, you give some code you reject:



const char* example() {return "123";}



With a little tweak, just for a bit of extra flexibility:



static inline const char* example() { return "123"; }



It's a little bit more cumbersome than the constant, but its all in one place (read as "easier to maintain") and should produce exactly the same code when used.
Parv
2011-07-16 03:00:57 UTC
Couldn't figure out what do u want to ask.

U said u don't care if it is const std::string or const char*, but in the main heading u r asking for it.



This is confusing.
2016-10-14 06:54:36 UTC
The function String::operator+() is a const function, which means it provides you to in no way adjust the /this/ merchandise, yet then you fairly're calling String::strengthen() which isn't const in any respect! (playstation : besides the glaring adjustments to operator+, which in real life could be a non-member function (see "C++ Coding standards"), i could evaluate utilising std::vector or std::unique_ptr, if your compiler enables it, for documents storage. extraordinarily for the momentary array in String::substr(). top now String::substr() isn't exception-secure: if String(sub) throws, delete []sub; is in no way pronounced as)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...