Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create new instance of a class without "new" operator

Tags:

Just a simple question. As the title suggests, I've only used the "new" operator to create new instances of a class, so I was wondering what the other method was and how to correctly use it.

like image 238
Sam Avatar asked May 04 '11 15:05

Sam


People also ask

Will you be able to instantiate the object without new operator?

In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object.

How do I create a new instance of a class?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.


2 Answers

You can also have automatic instances of your class, that doesn't use new, as:

class A{};

//automatic 
A a;             

//using new
A *pA = new A();

//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();

//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();

The last two are using placement-new which is slightly different from just new. placement-new is used to construct the object by calling the constructor. In the third example, malloc only allocates the memory, it doesn't call the constructor, that is why placement-new is used to call the constructor to construct the object.

Also note how to delete the memory.

  //when pA is created using new
  delete pA;

  //when pA is allocated memory using malloc, and constructed using placement-new
  pA->~A(); //call the destructor first
  free(pA); //then free the memory

  //when pA constructed using placement-new, and no malloc or new!
  pA->~A(); //just call the destructor, that's it!

To know what is placement-new, read these FAQs:

  • What is "placement new" and why would I use it? (FAQ at parashift.com)
  • placement new (FAQ at stackoverflow.com)
like image 107
Nawaz Avatar answered Oct 14 '22 00:10

Nawaz


You can just declare a normal variable:

YourClass foo;
like image 25
Björn Pollex Avatar answered Oct 14 '22 00:10

Björn Pollex