Can I call constructor explicitly, without using new
, if I already have a memory for object?
class Object1{ char *str; public: Object1(char*str1){ str=strdup(str1); puts("ctor"); puts(str); } ~Object1(){ puts("dtor"); puts(str); free(str); } }; Object1 ooo[2] = { Object1("I'm the first object"), Object1("I'm the 2nd") }; do_smth_useful(ooo); ooo[0].~Object1(); // call destructor ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
NO. You can't invoke a constructor without creating an object.
You can call a constructor manually with placement new.
Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. Constructor functions should only be called using new .
Sort of. You can use placement new to run the constructor using already-allocated memory:
#include <new> Object1 ooo[2] = {Object1("I'm the first object"), Object1("I'm the 2nd")}; do_smth_useful(ooo); ooo[0].~Object1(); // call destructor new (&ooo[0]) Object1("I'm the 3rd object in place of first");
So, you're still using the new
keyword, but no memory allocation takes place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With