Explicitly calling constructor

K

Kavya

Suppose I have class MyClass. Then which will be termed as explicit
call to constructor.

MyClass( );

or

MyClass object;
object.MyClass( );
 
A

Alf P. Steinbach

* Kavya:
Suppose I have class MyClass. Then which will be termed as explicit
call to constructor.

MyClass( );

or

MyClass object;
object.MyClass( );

The second line of the latter isn't valid code.

The first is an example of what the standard calls an explicit
constructor call, while the first line of the second example is a
declaration with an implicit constructor call.

Used as a stand-alone expression statement (some illuminating context
would be nice!) "MyClass();" creates a temporary of MyClass type and
calls the default constructor on that temporary.
 
O

Osamede.Zhang

Kavya said:
Suppose I have class MyClass. Then which will be termed as explicit
call to constructor.

MyClass( );

or

MyClass object;
When the object was declared,it was automatic initialized by calling
class's contructor.
 
F

Frederick Gotham

Kavya:
MyClass( );


That createless a nameless object which exists until the end of the
statement. The following two snippets are equivalent:

int main()
{
int i = MyClass().GetVal();
}

int main()
{
int i;

{
MyClass nameless_object;
i = nameless_object.GetVal();
}
}

If you would like to invoke a class's constructor, you need to supply it
with a memory address at which to construct an object of the class in
question. "Placement new" is used for this:

void *const pmem = malloc(512);

MyClass *const p = ::new((void*)pmem) MyClass();

p->~MyClass();

free(pmem);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top