Reputation: 215
here is the class definition (it's for exception handling):
class MyException {
public:
MyException(const char * pTxt) : pReason(pTxt){};
const char * pReason;
};
And later it is used as follows:
throw MyException("file too short");
after throw, is a new object created and initialized? Whatever the case, I don't understand how the class definition allows it to be initialized with a text string. It takes a pointer to a text string, doesn't it? And then sets pReason to that pointer, right? And how does this involve the line const char * pReason? I am confused, can anyone at least explain the class definition to me? I might be just looking past something obvious. I have copied the above code from "c++ for game programmers" page 90, btw.
Upvotes: 0
Views: 224
Reputation: 37066
A literal string in C++ IS a pointer to a string... in effect, sort of. A bit more pedantically, it's an array of characters, followed by a character of integer value zero. A character is an integer. Erm... In C++, a string literal is not an instance of the STL string class, std::string. This is fairly unusual among object-oriented languages, to say the least. It's an artifact of C++'s wild and reckless youth.
If you assign the string literal to anything (unless you use it as an initializer for an array), or pass it to a function, what gets assigned or passed is the address of the first character in the array -- a pointer to the string. And that's what you're seeing in the call to your constructor: What's being passed to the constructor is the address of the first character in the string literal, which is stored... wherever the compiler thinks it belongs. None of our business where that is.
This line declares pReason as a member variable of the class. The const part means you can't alter the string it points to (unless you go out of your way to do it, but you really shouldn't).
const char * pReason;
In C++, that's how you tell the compiler that your class will have a member with that type and that name.
Upvotes: 1
Reputation: 9091
const char* pReason is a declaration of a field. The constructor contains the initializer pReason(pTxt).
EDIT: I edit this post following the remark in the comment.
Upvotes: 0