I can simply call the destructor to delete this object.
No, you can't.
If you are in a member of a class, and you want to destroy that class's instance, calling
this->~ClassName() is a terrible idea that will almost always break.
Oh, this will call the class's destructor. But it will not destroy the memory associated with that class instance. So that memory allocation will leak.
If you are in a member of a class, and you are absolutely certain that this class instance was allocated with
new ClassName (and not
new ClassName or
new(someMemory) ClassName or
ClassName varName), then you can perform
Is there a way to tell the main class,from where I am creating these objects, about this event so that all this object references can be deleted ?
Well, you haven't said much about the nature of your system. You seem to have some "main class," and you have some "graph class". And you state that, when the "graph class" is destroyed, the "main class" needs to be notified so that "object references" can be "deleted" (ie: classes need to be destroyed).
If that's the case, then it seems to me that your problem is that this system has unclear ownership semantics. When one object has ownership over another object, then the destruction of the owning object will cause the destruction of the object being owned by it. Value containment (ie: non-pointer member objects) have this ownership relationship with the objects that contain them. Members of a class are destroyed when the class they are a member of is destroyed.
If these "object references" are objects that need to be destroyed when a graph is destroyed, then the graph should own those objects. And therefore, the graph itself should be responsible for destroying them. In C++11, such ownership relationships are usually expressed by classes like
So the graph object shouldn't have to inform anyone of anything. It should be responsible (uniquely or shared) for deleting them.
If these "object references" are just pointers you need to null out (because destroying the graph destroyed the objects they point to), then you have three choices:
Remove these "object references" pointers from the main class. Non-owning pointers are dangerous when your code's ownership semantics are muddied. And yours are.
Have the graph's destructor inform the main class that these objects are about to be destroyed. This would be done by getting a pointer to that class and calling a function.
Have the graph use
shared_ptr ownership of them, which allows the main class to use
weak_ptrs as their "object references".