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?
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory.
Member variables are members of the class itself. They are neither on the heap nor on the stack, or rather, they are where ever the class itself is.
Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create an object, it's always created in the Heap space.
The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free.
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);
}
Early note: use std::string
instead of a heap allocated char[].
Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation?
It will be heaped allocated in the constructor, the same way as in a stack allocated MyClass. It depends what you mean by "along with", it won't necessarily be allocated together.
And will the member be valid for the whole lifetime of MyClass object?
Yes.
As for the first example, is it practical to allocate class members on heap?
Yes, in certain cases. Sometimes you want to minimize the includes from the header file, and sometimes you'll be using a factory function to create the member. Usually though, I just go with a simple non-pointer member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With