Re: Explicitly calling constructors
On Jun 30, 6:55 am, Prasoon <prasoonthegr...@gmail.com> wrote:
Can constructors be explicitly called in a program without using
placement new???
Of course yes.
Foo *f = new Foo(); //Foo::Foo() called explicitly
Foo *f2 = new Foo(1,2); //Foo::Foo(int,int) called explicitly
Creation of an object is a two step process- (a) memory allocation,
and (b) Converting the raw memory into a valid "object". Constructors
are responsible for the second step, and "placement new" differs from
"new" as far as the only first step is concerned. The second step
(i.e. the constructor call) is common for both. IOW Placement new is
about "memory allocation" part of object creation process, and not
about the "construction of object from the raw memory".
As far as I know....considering the code snippet
#include<iostream>
class demo
{
public:
demo(){
std::cout<<"Constructor invoked";
}
~demo(){
std::cout<<"Destructor invoked";
}
};
int main()
{
demo d;//Constructor invoked
d.demo();//Compilation error
There is a compilation error above because constructors donot have
names. Hence, the so called member-function-call-like-syntax that has
the same name as the class doesnot call a constructor.
demo();//Creation of nameless object
d.~demo();//Allowed but may lead to undefined behaviour as the
local object
//d can be destructed twi=
ce
}
Is the creation of nameless object in the above code an explicit call
to constructor or not???
It actually depends on what is exactly meant by "explicit call to
constructor". Assuming that demo class had an extra constructor, say
demo(int), both of the following would qualify for "explicit call" to
constructor:
demo();
demo(4);
The reason I am saying these are explicit calls is that you are
"explicitly" telling the compiler which constructor is to be called.
According to me,its not. To call a constructor explicitly we need to
use Placement new but again it is not recommended to use "Placement
New"
IMHO, what is *actually* recommended is "not to use placement new
unless you have to". And that "unless you have to" clause indicates
that you are the best judge of whether it should be used in your
specific situation. http://www.parashift.com/c++-faq-lite/dtors.html#faq-11=
..10
Is there any other way of calling constructors explicitly????
Here is one example:
struct Foo {
explicit Foo(int s) { } //Explicit conversion constructor
};
const Foo& f = 5; //Error since Foo::Foo(int) is explicit
const Foo& f2 = Foo(5); //Ok, Constructor called explicitly, of course
not to be confused with "explicit" keyword.
Again, do you call this an explicit call to constructor?
I think that throughout this discussion, by "explicit call to
constructor" you mean that a constructor call without the first step,
i.e. memory allocation step. If that is what you mean, then placement
new is (AFAIK) the only way.