Create an object without a name in C++

Yes. By comparison to Java, you need to decide if you want to create it on the stack or on the heap. The former can have value semantics (behaves like an int -- copies/moves like an int, no polymorphic behavior), while the latter will have reference semantics (refers to the same object instance, can behave polymorphically, copy by cloning).

void ref( const X& x )       { x.do(); } // Reference semantics
void ptr( const X* const x ) { x->do();} // Reference semantics
void val( const X x )        { x.do(); } // Value semantics

int main()
{
    ref( X{} );     // Created on the stack
    ptr( new X{} ); // Created on the heap, but leaks!
    val( X{} );     // Created on the stack, moved rather than copied if available

    auto x = X{};   // Created on the stack
    ref( x );
    ptr( &x );
    val( x ); // Makes a copy of the object

    auto p = std::make_unique<X>(); // Created on the heap, doesn't leak
    ref( *p );
    ptr( p.get() );
    val( *p ); // Makes a copy of the heap object on the stack
}

Note: You can have polymorphic behavior with value semantics if you jump through some hoops. See, for instance, Louis Dionne's talk at CppCon17 on Runtime Polymorphism. If you don't jump through these hoops but try to use a value object polymorphically, you can end up with object slicing.


Yes you could do such a thing. As this is a temporary variable you don't need to name it, just as you did in Java.

The syntax will be:

function(Parameter());

If the class need parameter you just pass it to the temporary variable constructor:

function(std::string("hello"));

And finally, what you wrote for Java will work in c++ as well:

function(new Parameter());

But this will allocate the Parameter object on the heap, and in order to avoid memory leak, you will have to delete it inside function. But this is usually a bad idea.