Re: Create class using new?
On Nov 21, 2:29 pm, "mlt" <a...@asd.com> wrote:
I have the following class:
class Test {
public:
Test() {
a = 33;
}
private:
int a;
};
When I want to create an instance of this class in eg java I do:
Test t = new Test();
but in C++ I either do:
1) Test t;
or
2) Test t();
(what are the difference between 1 and 2?).
I can't do:
Test t = new Test();
new returns a pointer, since t is an instance of Test, you can't store
a pointer (to an allocated Test) into it, thankfully. This works:
Test* p_t = new Test();
....
delete p_t; // required
It is unwise to allocate on the heap unless absolutely necessary. And
when it is necessary its better to rely on RAII or smart pointers.
So this is better since it will allocate + invoke ctor + get
destructed automatically.
Test t; // allocated on the stack, not heap
but is that not the only way to make sure the instance lives after the
calling function has returned?
No, definitely not the way. Its shoddy programming to allocate
something over there and deallocate somewhere else. Managing the
lifetime of an object should either be automatic or given to a single
manager. In Java, your GC takes care of that while C++ uses a
different discipline. Java only uses the stack to store primitives, C+
+ can use the stack to store anything.