Number of ways to create an object

D

David White

Peter Ammon said:
A friend was asked "How many ways are there to create an object in C++?"
in an interview. Apparently, the "right" answer was eleven. Does
anyone know how the interviewer arrived at that number? Is this fact
well known (if true)?

On the face of it, one of these answers seems appropriate:
1. "Who cares?"
2. "You're wasting my time. Good day."

I seriously doubt that even Bjarne Stroustrup would have been able to give
them the number they were looking for. However, the question might be
cleverer than it looks. You can't rule out that an answer such as one of the
above (or a more polite equivalent) is what the interviewer is looking for.
Fumbling around nervously for the right number might be what rules you out.

DW
 
D

Deming He

jeffc said:
That "fact" is not well known, if true. Sounds like one of those goofy
questions where the interviewer has a "one up" by already researching an
obscure problem ahead of time that you couldn't know. Maybe he just wanted
to see how you think about things and get the ball rolling, not come up with
"11". (Frankly, I'm reminded of This Is Spinal Tap at this moment.)

class A;

A a; // 1
A* pA = new A; // 2
f(A()); // 3
etc.

Does all these below counted up to that magic number of 11?

class A;

// 1
// 2
// 3
////See Jeffc's 1, 2, and 3

A ff();// 4

class B
{
A a;
};//5

A b(a); // 6

char raw_mem[sizeof(A)];
void* place = raw_mem;
A* f = new(place) A();// 7

A* pA;
A* fff()
{
pA = new A;
}// 8

A* fff()
{
static A a;
return &a;
}// 9

A& ffff()
{
static A a;
return a;
}// 10


class B
{
static A a;
};

A B::a;// 11


Singleton // 12
Factory // 13

....
 
J

Jack Klein

The only meaningful answer is 1: by calling a constructor.

Lest idiots yet again object to that terminology: it's the one employed
by the Holy Standard.



Any number might be considered correct under suitable assumptions and
using suitable definitions, e.g. of "ways", "create", "object".

int main(void)
{
double d; // created an object!
return 0;
}
 

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,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top