3

I am trying to return a array of structs in my class but I keep getting an error

error C2556: 'cellValue *LCS::LcsLength(std::string,std::string)' : overloaded function differs only by return type from 'cellValue LCS::LcsLength(std::string,std::string)'

when I return in my .cpp file

My class declaration is:

enum arrow {UP, LEFT, DIAGONAL};

struct cellValue
{
    int stringLenght;
    arrow direction;
};

class LCS
{
public:
    cellValue LcsLength (string, string);
};

And when I try returning in my function I have:

cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}
2
  • Your code is incorrect but even if it were correct your array would be destroyed when the function ends Commented Apr 22, 2015 at 7:16
  • According to the the error message, your actual code contains both cellValue * LcsLength(std::string,std::string) and cellValue LcsLength(std::string,std::string). The code you posted will have different errors. Commented Apr 22, 2015 at 7:39

2 Answers 2

8

You have two main issues with your LcsLength function: your return type is wrong and you have a dangling pointer.

You declare LcsLength as returning a cellValue object, but then try and return a cellValue[1024][1024]. This is why you are getting your compiler error.

Regardless of the return type, what you are doing will not work, as table will be destroyed as soon as the function exits. You would be much better off using std::vector, or maybe std::map depending on what that table is for.

Sign up to request clarification or add additional context in comments.

Comments

2
cellValue LCS::LcsLength (string X, string Y)
{
    cellValue table[1024][1024];

    return table;
}

The problem here is in understanding that the local array table would decay into cellValue(*)[1024] and not cellValue which is what the function's return type is, as per the definition.

Another issue is, even if you fix the type issue, you'd be returning a local variable's pointer, which would be destroyed when the function goes out of scope and the callee would end up with a dangling pointer i.e. pointer to a loction no longer under your control.

You should go with std::array if you must return a collection of objects whose size required is known at compile-time, else go with Tartan's suggestion of using std::vector. You wouldn't be incurring any hit in performance too with C++11's guarentees.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.