constructor

U

uday

Can we create a object in c++ without calling a constructor?

what is answer to this. does this question means a private
constructor or different.
 
M

Mysidia

Not legitimately, and conceptually, no, an object is created when
a constructor is called over the memory area for the a object.

An exception is the POD types, plain old data C types, structs,
which can still be created with a call to 'malloc' [then released with
free]. There's no constructor there, but then, those aren't usually
considered objects.

In a context where the constructors are private, you can't instantiate
a new copy of the object with the ''new'' operator or create an object
as a stack variable:

this can actually be very advantageous if youi want to use a pool of
shared
copies of an object, instead of creating new ones...

i.e.

class Foo {
private: Foo() {}
public: class Foo* getInstance() {
static class Foo* globalInstance = NULL;

if (globalInstance == NULL)
globalInstance = new Foo();
/* if (globalInstance == NULL)
handle error */
return globalInstance;
}
};

See, now you have to follow some internally rules defined in the
class just to get a legitimate copy of the object :)

-Mysid
 
R

Ron Natalie

uday said:
Can we create a object in c++ without calling a constructor?

what is answer to this. does this question means a private
constructor or different.
You can't call a constructor period. A constructor is always
called for you when instantiating a class object. If there is
no constructor available (either implicitly or explicitly defined)
and accessible, the program is ill-formed.
 
R

Ron Natalie

Mysidia said:
An exception is the POD types, plain old data C types, structs,
which can still be created with a call to 'malloc' [then released with
free]. There's no constructor there, but then, those aren't usually
considered objects.

POD classes (to include) structs have constructors. You've just bypassed
it's call by bashing the void* value malloc() returns to some other type.

A struct isn't necessarily a POD, and certain classes can be POD.
 

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

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top