C++ - Does the Destructor just deallocate the memory or does it actually delete the object?

Viewed 3807

To check this, I have run this small test code.

#include <iostream>
using namespace std;

class name {
public:
  int data;
  name(int data) {
    this->data = data;
  }
  void printData() {
    cout << data << endl;
  }
};

int main() {
  name* namePointer;
  {
    name n(5);
    namePointer = &n;
  }
  namePointer->printData();
}

So, two questions:

  1. The name object n is created in the block inside main and its pointer is saved, to make sure its destructor is called when we get out of the block. But the pointer points to the same object and its member functions are still accessible. Doesn't this mean that the object isn't deleted yet?

  2. Say I add this to my name class:

    ~name() {
        cout << "destructor called" << endl;
    }
    

    Does overriding the destructor function, and doing nothing in it (here in ~name()), prevent the object from being deleted?

Edit: Thanks for the responses, it really helped. But May I know the reason for these down votes, I think this is a really good question. ¯_(ツ)_/¯

4 Answers
Related