Difference between calling a constructor with a pointer and without a pointer (instance)

I am new to C ++ and would like to know what is the difference between calling a constructor with a pointer and without a pointer. Without a pointer, I mean an instance of a class.

For example:

#include <iostream> 
using namespace std;

class abc {
    abc() {
        cout << "constructor";
    }

    ~abc() {
        cout << "destructor";
    }
};

int main() {
    abc a;
    return 0;
}

// VS
int main() {
   abc* a = new abc();
   delete a;
   return 0;
}

      

The only difference it calls dynamically and otherwise both are the same for example. get the same result?

+3


source to share


3 answers


abc a;

allocates a

on the stack by calling its default constructor. The destructor is called when a

out of scope.

abc* a = new abc();

allocates memory for an object abc

on the heap, calls its default constructor, and returns a pointer to the object. Remember to call delete a;

(which will call the destructor), otherwise you will leak memory.



abc a();

is a function prototype for a named function a

that returns abc

without taking any parameters.

+4


source


class {
....
}abc;

abc a;
abc *a = new abc();

      

In both situations, the class constructor is called because you are instantiating the object. But there are other subtle differences as well.



  • abc a;

    This is where the object is allocated on the stack (if you declare it in your main or other function), OR in the .data section if you declare it globally. In any case, memory is allocated statically; memory management needn't worry.
  • abc *a = new abc();

    Now you are allocating memory dynamically for your object and you need to take care of memory management yourself, i.e. call delete () or a memory leak in your program.

But there is another difference between the two ways to create an object: in the second example, you are also calling operator new

. Which can be overwhelmed to give you different behavior. Also, since the second call includes the new operator, you can use placement new

and allocate your object in the memory location of your choice - you can't do that from the first example.

+1


source


Dynamic allocation can be broken down into two parts:

abc *a; // doesn't call the constructor
a=new abc(); //calls the constructor

      

You will find this type of allocation more useful when you learn about run-time polymorphism (i.e. a pointer to a class can contain an object of another class).

NB: Your program, as written here, will not compile because the constructor is private.

0


source







All Articles