Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call constructor with class instance pointer?

Tags:

c++

We can call destructor explicitly through class pointer, why not constructor? Any idea?

#include <iostream>

class Con {
public:
    Con( int x ) : x( x ) {

    }

private:
    int x;
};

int main() {
    Con* c = new Con( 1 );
    //c->Con( 2 ); //illegal
    c->~Con(); // ok!
    delete c;
}

Thanks,

like image 353
Chan Avatar asked Apr 27 '11 15:04

Chan


People also ask

Do pointers call constructors?

A pointer does not refer to any object until you provide it with an address; therefore, no constructor is called.

Is pointer to constructor possible?

If you had a pointer to a constructor it would either have to be a static pointer, something like a factory function, or a special pointer to something that would be called immediately after memory allocation. It could not be an ordinary member function and still work as a constructor.

Can you call constructor in class?

No this is not possible. You cannot assign to this.

Can you call a constructor directly?

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.


2 Answers

You can actually call it, it is just that the syntax is not that of calling a member method (of which the destructor is an special case), so it is not done with the member access operators. Rather you have to resort to the placement-new syntax:

Con c;
c.~Con();        // destroy, now c is not a Con anymore
new (&c) Con();  // recreate, now c is a Con again

As a particular case, in the C++0x proposal, that is actually used in one of the code examples, providing means to reuse a union as a different type in the event of an union containing non-POD elements:

union U {
   int i;
   float f;
   std::string s;
};

int main() {
   U u;
   new (&u.s) std::string( "foo" );
   u.s.~string();
   u.i = 5;
}

}

like image 147
David Rodríguez - dribeas Avatar answered Oct 16 '22 18:10

David Rodríguez - dribeas


No. You cannot.

Con* c = new Con( 1 );
//c->Con( 2 ); //illegal

You've already called the constructor in the new expression.

By the time you've a valid pointer of type Con*, you've already created an object. And calling constructor on the "constructed" object doesn't even make sense. So why would C++ allow that?

like image 21
Nawaz Avatar answered Oct 16 '22 17:10

Nawaz