If a class is declared as follows:
class MyClass
{
char * MyMember;
MyClass()
{
MyMember = new char[250];
}
~MyClass()
{
delete[] MyMember;
}
};
And it could be done like this:
class MyClass
{
char MyMember[250];
};
How does a class gets allocated on heap, like if i do MyClass * Mine = new MyClass();
Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation? And will the member be valid for the whole lifetime of MyClass object?
As for the first example, is it practical to allocate class members on heap?
Yes, yes, and yes.
Your first example has a bit of a bug in it, though: which is that because it one of its data members is a pointer with heap-allocated data, then it should also declare a copy-constructor and assignment operator, for example like ...
MyClass(const MyClass& rhs)
{
MyMember = new char[250];
memcpy(MyMember, rhs.MyMember, 250);
}