C++ – How to have a Destructor inside a Structure in C++

c++

I have a struct which has a pointer. It is always dynamically allocated. So I need to always need to free up the pointer whenever the object is created like this.

A obj;
obj->nums = new int(5);
delete obj->num;

struct A
{
    int *num;
    char c;
    int val;
};

Can I have a destructor inside A to manage the cleanup of the pointer variable. Can I have the destructor even though I don't have a constuctor; So my new code looks like:

struct A
{
    int *num;
    char c;
    int val;
    ~A()
    {
       delete num;
    }
}A;

Best Answer

Yes. A struct in C++ is a class, but with default public access, and with default public inheritance. Hence, a struct can have constructors, destructors, member functions, etc.

struct A {
    int b;

private:
    int c;
};

Offers identical member access to:

class A {
public:
    int b;

private:
    int c;
};

The difference in inheritance can be readily demonstrated.

struct As { int b; };
class Ac { public: int b; };

These look identical given that everything in Ac is public. And indeed, these will behave identically. Until we bring inheritance into play:

struct Bs : As { };
class Bc : Ac { };

Bs and Bc are not equivalent.

Bs x { 3 };

The above will compile, but the following will not.

Bc y { 3 };

In order to make this work equivalently, we need to explicitly state that public inheritance is used:

class Bc : public Ac { };

As noted, your struct should handle the dynamic allocation in the constructor.

struct A
{
    int *num;
    char c;
    int val;
   
    A(int n) : num(new int(n)) {}
    ~A() { delete num; } 
};

As your struct contains dynamically allocated memory, you also need to read up on the rule of three/five/zero.