Alex Rivera | Logout

Am I initializing my C++ reference variables correctly?

Asked 2009-04-15T16:13:59.220
20

I've tried to Google this issue, and I can't find anything that I see as relevant. So I must be looking for the wrong thing; none the less, I'd appreciate some advice...

Foobar &foobar = *new Foobar(someArg, anotherArg);

Is it just me or does that seem smelly?

I understand that the new keyword is designed for use with pointers (as such):

Foobar *foobar = new Foobar(someArg, anotherArg);

But what if you don't require a pointer on that instance, and you would like to use a reference instead? Or, is it the case that you don't need to explicitly initialize it (much like local variables); and if this is the case, what if I want to initialize with parameters?

The following does not work (unless I'm doing something wrong):

// the last argument is of type: int
Foobar &foobar(someArg, anotherArg);

... gives the compiler error:

initializer expression list treated as compound expression invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘int’

And also this doesn't seem to work:

Foobar &foobar = Foobar(someArg, anotherArg);

... gives the compiler error:

error: invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘Foobar’

Update 1:

Bare in mind that I am returning this value, so I don't want to use a local variable; I want to use a value on the heap, not the stack:

Foobar &helloWorld()
{
    Foobar &foobar = *new Foobar(someArg, anotherArg);
    foobar.HelloWorld();
    return foobar;
}

Should I just be using pointers instead, or is this completely valid?

Edit
Report

1 Answer

1

Nope, you've got it. A foo& "points to" the actual object, so if you really want a foo reference you have to dereference the foo pointer.

@Neil has a point, though -- syntactically that's how you get what you want, but why do you want it?

answered 2009-04-15T16:18:07.260

Your Answer