To delete a pointer, the value of the pointer has to be stored until the point of deletion. Since the pointer data
only exists until the constructor returns, and no copies are made of the pointer value, the pointer cannot be deleted after the constructor returns. Since it wasn't deleted before that, the allocated memory will have leaked.
Furthermore, a variable cannot be accessed outside of its scope. data
is a local variable of the constructor, and cannot be accessed outside of that function. There is no variable data
in the destructor; hence the error from your compiler.
So, if you do allocate something in a function, and don't wish to deallocate it within that function, you must store the pointer somewhere. Since the function where you allocate is a constructor, it would be natural to store the pointer in a member variable. The destructor can access member variables and would therefore be able to delete the pointer.
However, keep in mind that it is extremely rare for C++ programmer to need to do manual memory management. It should be avoided as much as possible. For example, in this case, it would be smart to use std::vector
to allocate a dynamically sized array.