Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initialization without "new" C++

I am wondering a bit about object initialization in C++. I read using the 'new' keyword should be avoided if possible, since I don't need what it offers (dynamic allocation, right?), and I don't want to have to delete the object manually. I am having troubles calling the initialization of my object without using new though. I have this class:

class Apodization {

public:
    Apodization()
    {
    std::cout << "Constructor for Apodization" << std::endl;
    }
}

and this code:

Apodization* apoObj();
// Apodization* apoObj = new Apodization();

The print happens as expected when using new to create the object, but not without. I'm guessing this is because I'm only creating a pointer of Apodization type in the example above, but I don't know where to go from there. I would like to know the proper way to initialize an Apodization object without using the new keyword. Thanks for the help! I am finding C++ classes a bit weird coming from Java and Python.

like image 790
Callum C Avatar asked Dec 02 '22 16:12

Callum C


2 Answers

An Object is initialised without new using RAII (Resource Allocation is Initialisation). What this means is that when you declare an instance of Apodization, memory for the instance is allocated on the stack and then the constructor is called to set up the initial state.

This means that simply writing:

int main(){
   Apodization apodization;
   //apodization.doSomething();
   return 0;
}

is all you need to get the ball rolling! (Being a Java guy myself, I love the succinctness of this!)

As the object is allocated on the stack, the destructor will automatically be called at the end of the scope; no manual memory management required.

P.S. I highly recommend you read Bjarne Stroustrup C++11 Programming Guide!

like image 178
W.K.S Avatar answered Dec 17 '22 12:12

W.K.S


You can't. The new operator allocates memory for an object, calls the constructor for that object, and then returns the pointer. In your code, all you are doing is declaring the pointer without any memory being set aside for it, or a constructor doing any work. It is just a pointer to nothing.

like image 28
Lawrence Aiello Avatar answered Dec 17 '22 14:12

Lawrence Aiello