Home > Blockchain >  Why constructors and destructor are not called when pointer is created & destroyed?
Why constructors and destructor are not called when pointer is created & destroyed?

Time:08-12

Why constructors and destructor are not called when pointer is created & destroyed ? I m really confused because pointer is also an object just like normal object..memory is also allocated for pointer..then why constructor and destructor is not called of class

CodePudding user response:

There is nothing to do in the construction of pointer objects, in much the same way as there is nothing to do in the construction of int objects, or of objects of a class that has a trivial constructor.

You can think of it like the (lack of) constructor for

class Trivial {
    int member;
};

CodePudding user response:

Creating a SomeClass calls the constructor of SomeClass if it has one. Creating an int calls the constructor of int if it has one. Creating a SomeClass * calls the constructor of SomeClass * if it has one.

You can write a constructor for SomeClass and then it will call it. int doesn't have a constructor so it doesn't call one. SomeClass * doesn't have a constructor so it doesn't call one.

SomeClass * isn't the same as SomeClass

Same for destructors.

(this explanation is simplified a bit)

CodePudding user response:

Why constructors and destructor are not called when pointer is created & destroyed?

Because a pointer is not an object of type SomeClass but instead an object of type SomeClass*. In other words, when we create a pointer to some class-type say SomeClass then we're not creating an object of type SomeClass but of SomeClass*.

Constructor are called when an object of type SomeClass is created.

Basically,

//type SomeClass* is not the same as the type SomeClass
SomeClass* != SomeClass
  • Related