If you do the second you will create a memory leak. Which is bad and you should simply never do it.
Think in the way things actually happen. Lets say you have this
Code:
void foo()
{
int* my = new int;
}
when foo is called a local variable "my" will be allocated. "my" has a type of a "int*".
So you will have when "int* my" is called
Code:
LOCAL FOO
address value
my some random value
when the " = new int" is called you will have
Code:
LOCAL FOO
address value
my 0x123
HEAP
address value
0x123 some random value
that said, when "foo" returns the local variable "my" is deallocated. So you have a "some random value" in the address 0x123, but that address cannot be accessed because the pointer is de-allocated. Memory leak.
If you modify foo you could do
Code:
int* foo()
{
int* my = new int;
return my;
}
now, with the above numbers, foo() would return the value 0x123. "my" will still be de-allocated, but you can assign the value 0x123 to another variable. Thus saving the memory address of the memory allocated by "new int".
Remember, the golden rule.
-For each new you need a delete
Thus, whatever you allocate dynamically, you have to de-allocate yourself. The same with malloc()/free() in C.
C++ offers destructors. You should study them a bit because they are the main mechanism for automatic memory management. As mentioned, the standard containers, like vector<> de-allocate memory automatically with the destructor so you won't have to worry about it.
For your initial example. Lets say
Code:
class A
{
public:
int* a;
...
int* z;
A() {
a = new int;
...
}
};
int main()
{
A myA;
}
than this
Code:
class B
{
public:
int a;
...
int z;
...
};
int main()
{
B* myB = new B;
}
A will call a lot more times new. Which might be slower and less efficient than calling new once for B. But the result is not the same. Object B will entirely be allocated on the heap, pointed by "myB". Object A will be allocated in local space of main(). So the object pointer and all its member variables (int* a....int* z) will be in the local space of main(). All the objects those member variables point to will be allocated on the heap. So you will need to call delete that many times.
You might think that B is better. But I would say that most of the time it is not. Cause, you can use a combination of the two and do something like:
Code:
class A
{
public:
B* myB;
A() {
myB = new B;
}
}
int main()
{
A myA;
}
The benefit? You call new once again. But now you can use a destructor to do the de-allocation automatically. You would simply add
Code:
class A
{
public:
B* myB;
A() {
myB = new B;
}
~A() {
delete myB;
}
}
What happens is that when "myA" is de-allocated automatically when main() returns, the destructor is automatically called. The destructor will de-allocate the internal object B. Which needs to be manually de-allocated since it was allocated with new. Thus, with this chain reaction everything is deleted. Thus, using destructors is most of the times the "clever" solution.