views:

71

answers:

3

Hi i want to do the next

instead of

MyClass object;
 function_x (object);

i want to

function_x ( new object );

so what will be the structure of the MyClass to be able to do that .. if i just compiled it , it gives me a compile time error


answer function_x (MyClass() )

New Edit thanks for the quick answers.. i did ask the wrong Question i should have asked how

temporary variables created in C++ and the answer

+3  A: 

new is called on classes, not objects. And it returns a pointer, so unless function_x accepts a pointer, this is impossible.

You can do this though:

void function_y(MyClass* ptr)
{
  // Do something
}

// Then call
function_y(new MyClass);

Note a few things about this:

  1. The default constructor of MyClass is called when it's created
  2. function_y must keep the pointer in some accessible place to avoid a memory leak

Is this what you need, or something else?

Eli Bendersky
yes sorry i mistakenly wrote it new object it should be new class but after another search i searched for something called ( temporary variables ) which what i needed in first place but couldn't be verbose (pardon my bad english )so the temporary objects are something like:function_x ( MyClass() ) directly and there is no new operator .. when i was programming in java we used new MyClass
ismail marmoush
+1. You might want to add a little more about memory leaks, the concept of ownership and balancing `new` with `delete`.
outis
A: 

new object returns object*, so the signature for function_x should be:

void function_x(object* obj) {
}

And you can only call operator new on a class, not instances of a class.

Igor Zevaka
A: 

As per edit, if you want to create a temporary object you can like this:function_x (MyClass ()); . Note that you can not modify this temporary object so your function_x should take this parameter by const-reference.

Naveen