I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.
To learn that, I have made the following simple code. It c
Your problem is in this line right here:
*pointer = a;
All the stuff that normally happens in your default constructor hasn't happened yet, including the allocation of memory for *pointer
.
The fix is to allocate memory for an integer. You can use malloc
and friends or new
for this, but make sure it's the same method you use in your default constructor, because you only get one destructor, and the calls have to match.
If a member-wise (shallow) copy is okay, then you don't have to do anything. If you want a deep copy, you have to allocate new storage for copies of all the members.
If you want to do a deep copy, you of course must also allocate new memory to hold the values. If the original has a pointer to an int, and you don't want the copy to use the same pointer value, you must allocate new memory to hold an int, and then copy the value there.
Your example is not very clear, it doesn't show the implementation of your copy constructor, or how the pointer
member gets initialized.
I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.
It is not completely true. When you have pointers in your class and allocate the memory using new
then you have to worry about copy constructor. Also, don't forget the assignment operator and destructor.
You have to delete the memory allocated using delete
.
It's called Law Of The Big Three.
Example:
~Matrix(); //Destructor
Matrix(const Matrix& m); //Copy constructor
Matrix& operator= (const Matrix& m); //Assignment operator
More often than not, if YOU need to write a copy constructor or assignment operator you're doing something wrong. Leave the copy constructors and assignment operators to the implementers of the standard library. Compose your classes of already-copyable and assignable elements and you won't have to write your own.
For example, maybe that int * member should be a std::vector instead.
If you can't make the class default copyable/assignable, maybe you can make it non-copyable/assignable by declaring, but not implementing, a private copy constructor and assignment operator.
Only if none of the above are feasible should you implement your own copy constructor or assignment operator.
I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor
More often than not it is a good idea to simply disable it by declaring it (and the assigment operator) private and not implementing it.