Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deletion of pointer to incomplete type 'Point'; no destructor called

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!

like image 540
Alon Shmiel Avatar asked Apr 04 '13 22:04

Alon Shmiel


People also ask

Can we delete this pointer in destructor?

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.

Does delete destroy the pointer?

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.

Do I need to deallocate a pointer?

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 .


2 Answers

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.

like image 112
Kerrek SB Avatar answered Sep 28 '22 11:09

Kerrek SB


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 #includes Point.h.

like image 36
Ed S. Avatar answered Sep 28 '22 12:09

Ed S.