I have 2 files:
Point.h
:
class Point {
int x;
int y;
char* name;
public:
Point() { name = new char[5]; }
~Point() { delete[] name; }
};
and: Line.h
:
class Point;
class Line {
Point* p;
public:
Line() {
p = new Point[2];
....
...
}
~Line() {
delete[] p;
}
};
but when I compile, I got the next error:
deletion of pointer to incomplete type 'Point'; no destructor called
any help appreciated!
Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword. As, delete can only be applied on the object that has been created by using “new” keyword only.
Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
Pointers to variables on the stack do not need to be deleted. They become invalid on their own when the function the variable is in returns. Pointers to memory created using new should be deleted using delete .
You need to add #include "Point.h"
into your file Line.h
. You can only construct and delete complete types.
Alterntively, remove the member function definitions from Line.h
, and put them in a separate file Line.cpp
, and include Point.h
and Line.h
in that file. This is a typical dependency reduction technique which makes code faster to compile, although at a potential loss of certain inlining opportunities.
You have forward declared Point
, which is fine for declaring a pointer or reference, but not fine for anything else in which the compiler would need to know the definition of the forward declared class.
If you need the forward declaration in the header file (do you? If not, just #include "Point.h"
in Line.h
) then implement your Line
functions in an implementation file which #include
s Point.h
.
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