On Sunday 30 March 2003 09:54 am, Derek Fountain wrote:
How would I set HelloClass::str to something within the class definion, or constructor? IOW, how do I initialize member variables of user defined types to default values?
Just write your constructor like this:
HelloClass::HelloClass() { str = "Default string"; }
Or do I misunderstand the question?
OK, now that I have the name space stuff straightened out, that works for me. I was trying things with /new/ and mixing in the namespace resolution syntax, which wasn't working. At this point, I don't even want to think about why. I also got a compile error when I left out the explicit declaration of the constructor, but that was immediately obvious. The next thing I need to figure out is the difference between class HelloClass { ... private: string str; } and class HelloClass { ... private: string * str; } I know one is a pointer, and the other is simply a class member of type /string/. I just need to figure out how the two differ in behavior. I've discovered places where I was able to declare pointers in classes, but not members of the type referred to by the pointer. I'm pretty sure it has to do with how the constructors of the member types behave, I'm just not sure what exactly is causing the problems. If I can't figure it out, I'll see if I can formulate a good example to demonstrate the problem. This is, IMO, the kind of Hello World that should be a standard example for working with the string class, perhaps with a good example of a pointer to a string being used as well: #include <iostream> // cout, cin #include <string> using namespace std; class HelloClass { public: HelloClass::HelloClass(); void sayHello(); void setMessage(char * message="Hello C++ World. Default setMessage."); private: string str; }; void HelloClass::setMessage(char * message){ str = message; } void HelloClass::sayHello() { cout << str << endl; } HelloClass::HelloClass(){ str = "Hello C++ World. Declared in constructor."; } main() { HelloClass h; h.sayHello(); h.setMessage(); h.sayHello(); h.setMessage("User defined \"Hello World\" message."); h.sayHello(); return 0; }
-- "...our desktop is falling behind stability-wise and feature wise to KDE ...when I went to Mexico in December to the facility where we launched gnome, they had all switched to KDE3." - Miguel de Icaza, March 2003