I mean, if i have some class like:
class A{
int* pi;
};
*A pa;
when i call delete pa
, will pi
be deleted?
You need to define a destructor to delete pi;
. In addition you also need to define a copy constructor and assignment operator otherwise when an instance of A
is copied two objects will be pointing to the same int
, which will be deleted when one of the instances of A
is destructed leaving the other instance of A
with a dangling pointer.
For example:
class A
{
public:
// Constructor.
A(int a_value) : pi(new int(a_value)) {}
// Destructor.
~A() { delete pi; }
// Copy constructor.
A(const A& a_in): pi(new int(*a_in.pi)) {}
// Assignment operator.
A& operator=(const A& a_in)
{
if (this != &a_in)
{
*pi = *a_in.pi;
}
return *this;
}
private:
int* pi;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With