Andrei Sevtsenko
Andrei Sevtsenko

Reputation: 223

Error: expected unqualified-id before '&' token

I'm currently working on a uni assignment and in it we create Task objects and assign successor and predecessor Tasks to each to chain them together. When I try to return a successor or predecessor, I keep getting this error (as in the title) Here's the Task.h relevant sections:

class Task {
private:    
/**
 * The set of predecessor tasks for this task.
 * Can be empty.
 */
std::vector<Task*> task_from;
/**
 * The set of successor tasks for this task.
 * Can be empty.
 */
std::vector<Task*> task_to;

Here is the Task.cpp file relevant sections (method pulls Task out of array at given index):

Task& Task::successor(int index) const {
    if (index < 0) throw TaskException("");
    Task temp = this->&task_to.at(index);
    return temp;
}

Note that the method signatures are pre-defined for the assignment and we can't change them, just the code inside the braces is ours to write.

Also, if I don't include the '&' in this->&task..., I get the error "Types 'Task' and 'Task*' are not compatible"

Upvotes: 0

Views: 2405

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117926

You are trying to return a function-local variable by reference, which will leave you with a dangling reference as soon as you return from the function. If you are trying to get a reference to the Task in your vector, your successor function would look like

Task& Task::successor(int index) const {
    if (index < 0) throw TaskException("");
    return *task_to.at(index);
}

Know that this does not check that the Task* at that index is not nullptr.

Upvotes: 2

Related Questions