Ronyco123
Ronyco123

Reputation: 87

Pointer to object and destructor

I am trying to understand why my code doesn't use destructor of class Name. In fact I write two classes. First one called Name and a second called Person that have a pointer to object Name. What I don't understand is why the program doesn't called to the destructor of Name, because I think when I write "new" I create a new object so it has to call to the destructor of class Name before closing program.

Can you explain what wrong in my understanding. Thanks !

class Name
{
private:
    string name;
public:
    Name(string name) : name(name) { cout << "Hello " << name << endl; }
    ~Name() { cout << "See you soon " << name; }
};
class Person
{
private:
    Name* myname;
public:
    Person(string name) { myname = new Name(name); }
    ~Person() { cout << "Exit" << endl; }
};

int main()
{
    Person("Marc");
    Person("Alex");
}

Upvotes: 1

Views: 84

Answers (2)

Devolus
Devolus

Reputation: 22094

You are creating a memory leak here, because you create a new instance of Name here

Person(string name) { myname = new Name(name); }

but you never delete it. This is the reason why the destrcutor of Name is never called.

To avoid this you can use an std::unique_ptr or an std::shared_ptr, which will automatically handle the lifetime of such an object.

std::unique_ptr<Name> myname;
Person(string name) { myname = std::make_unique<Name>(name); }

An alternative is to delete the object in your destructor, but in C++ you should avoid direct handling of dynamic raw pointers.

#include <iostream>
#include <memory>

class Name
{
private:
    std::string name;

public:
    Name(std::string name) : name(name) { std::cout << "Hello " << name << std::endl; }
    ~Name() { std::cout << "See you soon " << name << std::endl; }
};
class Person
{
private:
    std::unique_ptr<Name> myname;

public:
    Person(std::string name) { myname = std::make_unique<Name>(name); }
    ~Person() { std::cout << "Exit" << std::endl; }
};

int main(int argc, char **argv)
{
    Person("Marc");
    Person("Alex");

    return 0;
}

Upvotes: 3

Talal02
Talal02

Reputation: 162

As myname object in Person's class is a pointer. For every pointer there must be a delete statement to deallocate the memory.

Replace Person's class Destructor as:

~Person() { 
        cout << "Exit" << endl;
        delete myname;
    }

Upvotes: 1

Related Questions