PDA

View Full Version : Char Arrays as Class Members



Atomic_Sheep
27th January 2013, 05:38
Been reading about chars, and arrays and all that for a while now, and googling my questions but still can't figure this one out:

1.) How to go about creating a char member variable in a class. I've got a member variable:


char chString[];

and a member function:


void AddString(char chText)
{

}

What do I need to do in the add text function to be able to add text to the member variable?

2.) And is there some way of creating a constructor that would allow me to populate the char string member from the get go? Simply doing this isn't working


Field(char chFieldText) : m_chText(chFieldText)
{}

Tros
27th January 2013, 18:07
Members of C++ classes need to stay of a static size, and must be programmed to use the heap if they want to have variable length members.

e.g.
class ExClass_A
{
private:
char chFieldText[256]; //Works fine for what you want to do, assuming you're okay with always taking up 256 bytes, and never going over 256 bytes.
}

class ExClass_B
{
private:
char chFieldText[]; //Is equivalent to "char *chFieldText", which has scope-issues*.
}

class ExClass_C
{
private:
QString chFieldText; //This isn't a c-primitive, and doesn't come with the limitations of scope, copying. It relies on the heap to efficiently store variable-length text, but hides most of that management from the programmer.
}

class ExClass_D
{
private:
vector<char> chFieldText;// This would be the pure C++ form. Or you could use "string" instead of "vector<char>", which is also better and pure C++. Both vector and string (which is effectively vector) use the heap for space-efficient storage, but a lot of that magic is hidden away from the programmer.
}



If you're using QT, I recommend QString.