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
if it has a pointer to a regular type then
A::A(const A& a):
pointer_( new int( *a.pointer_ ) )
{
}
if it has a pointer to some base class then
A::A(const &a ):
pointer_( a.pointer_->clone() )
{
}
Clone is a implementation of a prototype pattern
Don't forget to delete the pointer in the destructor
A::~A()
{
delete pointer_;
}
To fix your example
TRY::TRY(TRY const & copyTRY){
int a = *copyTRY.pointer;
pointer = new int(a);
}
With the statement int* pointer
you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: int* pointer = new int
. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't forget to release the memory using delete in the destructor.
I hope this example helps:
class B
{
public:
B();
B(const B& b);
~B();
void setVal(int val);
private:
int* m_p;
};
B::B()
{
//Allocate the memory to hold an int
m_p = new int;
*m_p = 0;
}
B::B(const B& b)
{
//Allocate the memory first
m_p = new int;
//Then copy the value from the passed object
*m_p = *b.m_p;
}
B::~B()
{
//Release the memory allocated
delete m_p;
m_p = NULL;
}
void B::setVal(int val)
{
*m_p = val;
}
When writing a Copy Constructor, you should allocate memory for all members. In your case:
TRY::TRY(TRY const & copyTRY){
pointer = new int(*(copyTry.pointer));
}
Operator= is somehow similar, but with no memory allocation.
TRY& operator=(TRY const& otherTRY){
this->a = *(otherTry.pointer)
return *this
}