C++ Blog

Saturday, October 08, 2005

What one should take care, when writing a C++ class with pointer members?

a. Mainly constructor, Copy constructor (for deep copy), assignment operator and destructor,
b. If a class which has pointer members is inherited then the destructor should be made virtual.
c. Memory leak is the main concern so de-allocation of memory is really import if there is a pointer member.

1 Comments:

At 10:48 AM, Blogger Unknown said...

Actually, your second point is incorrect: "b. If a class which has pointer members is inherited then the destructor should be made virtual."

A destructor needs to be virtual whenever a class is going to be used polymorphically:

class A { /* ... */ };
class B : public A { /* ... */ };

void func()
{
A* a = new B;
// use a
delete a;
// If class A doesn't have
// a virtual destructor, then
// the call to delete a will
// not invoke the destructor
// in B, as desired.
}

It seems you understand this, but I'm confused why you think this is related to whether the class has pointer members or not, the contents of a class are not relevant to whether it requires a virtual destructor or not, only how you intend to use it. There are many instances of classes with pointer members and no virtual destructor (std::vector springs to mind), and vice versa.

Have a good day,
M

 

Post a Comment

<< Home