user2421725
user2421725

Reputation: 77

C++ return a pointer to a class

I have a class.

I need to create a function that returns a pointer to a member of this class.

My class looks like this:

class clsNode
{
private:
    wstring m_grapheme;
    vector <clsNode*> m_Daughters;
public:
    clsNode *getNextNode(const udtCharVec &u);
};

I tried the following:

clsNode *clsNode::getNextNode(udtCharVec &u)
{

    if (u.Grapheme == m_grapheme)
    {
        return *m_Daughters[0];
    }
    else
    {
        return *m_Daughters[1];
    }
}

The compiler tells me "error c2511: clsNode:getNextNode(udtCharVec &): Overloaded member function not found in clsNode."

Can somebody tell me where I made a mistake? Thank you!

Upvotes: 1

Views: 128

Answers (3)

Shoe
Shoe

Reputation: 76298

I think you meant:

return m_Daughters[0];
//    ^

because m_Daughters[0] is of type clsNode* and *m_Daughters[0] would be of type clsNode which would mismatch the return type.

Also your function signature is different in the definition and implementation:

clsNode *getNextNode(const udtCharVec &u)
//                   ^^^^^
clsNode *clsNode::getNextNode(udtCharVec &u)

Upvotes: 4

sdkljhdf hda
sdkljhdf hda

Reputation: 1407

You have several mistakes here. First you have declaration

clsNode *getNextNode(const udtCharVec &u);

which means that the function takes its argument by reference to const, whereas when you define the function you have this

clsNode *clsNode::getNextNode(udtCharVec &u)

The signatures are different (notice the lack of const in the second one).

The second problem is in the return statements:

return *m_Daughters[0];

type of the returned value is a reference, not a pointer (the * there dereferences the pointer that you get from the vector). To fix this, do this:

return m_Daughters[0];

Upvotes: 2

Dave B
Dave B

Reputation: 186

The method signature in the class declaration is: clsNode *getNextNode(const udtCharVec &u);

but the implementation below is: clsNode *clsNode::getNextNode(udtCharVec &u)

Note the "const" in the declaration. The compiler is telling you it can't find the declaration for the one you implemented at the bottom

Upvotes: 1

Related Questions