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
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;
}