I just started working with C++ and now I have a really basic question.
I wrote 2 classes:
Coordinate:
#include <stdio.h>
class Coordinate {
private:
int x;
int y;
public:
Coordinate(int a, int b) {
x = a;
y = b;
};
void printTest() {
printf("%d %d\n", x, y);
};
};
Test:
class Test {
private:
int q;
Coordinate *point;
public:
Test(int a, int b, int c) {
q = a;
point = new Coordinate(b, c);
};
virtual ~Test() {
delete point;
}
};
main function:
int main() {
Test *test = new Test(1, 2, 3);
// ...
delete test;
return 0;
}
In my main
I worked with an object of the Test
class. I wrote my own Test
destructor but I am not sure if this destructor work like expected. Does it completly deallocte the memory from test
? Or do I have to do something with the q
attribute to deallocate it?
Test test(1, 2, 3);
andCoordinate point;
work as is without any extra effort, thoughpoint
would require properly using a member initializer list instead of attempting to construct a default and then reassign it. – ChlortetracyclineTest test = Test(1,2,3);
instead ofTest* test= new ...
– Cavessonnew
, anddelete
. C++ supports value semantics which makes object cleanup automatic. – Endlongdelete
for everynew
.q
is automatically allocated and will therefore be automatically deallocated. – Lydgatestd::shared_ptr
andstd::unique_ptr
. They are efficient and you then don't have to bother withdelete
. – Insufflate