variables initialization in the constructor
-
let's say i have a class like this: class a { private: char name[10]; . . . } how do i give 'name' a value in the constructor? chen.
name = {"10 chars long"}; OR name = new char[10]; ::strcpy(&name[0], "value"); // going from memory, args could be the wrong way around If you use the second method, don't forget to release memory in the destructor. If you use the first, don't change the value of the string, which means it should be const. Overall, you'd do better to use a string class to hold the value, if practical. Christian Graus - Microsoft MVP - C++
-
let's say i have a class like this: class a { private: char name[10]; . . . } how do i give 'name' a value in the constructor? chen.
If you get the name from the outside, go with this:
class a( const char* a_name) { strcpy(name,a_name); // note: unsafe ;-) }
However, if you know the name at compile time already, simply hard-code it - gives more speed and security.class a { const char* get_name() const { return "blabla"; } }
---------------------- ~hamster1 -
let's say i have a class like this: class a { private: char name[10]; . . . } how do i give 'name' a value in the constructor? chen.
Instead of using a char array, consider a
string
class:class a
{
private:
std::string name;
.
.
.
};And then a constructor may look like:
a::a(const char* yourName) : name(yourName)
{}
My programming blahblahblah blog. If you ever find anything useful here, please let me know to remove it. -- modified at 8:32 Tuesday 30th August, 2005