bas
bas

Reputation: 1678

invalid conversion from pointer to const pointer

I have the following class

File Node.c

std :: vector<NodeConnection*>* Node :: GetConnections() const
{
    const std :: vector <NodeConnection*> * output = &this->connections;
    return output;
}

file Node.h

class Node {
    private:
        std :: vector <NodeConnection*> connections;
    public:
        std :: vector <NodeConnection*>* GetConnections() const;
};

I am trying to convert the vector connections to a const pointer. However, I keep getting the error

[Error] invalid conversion from 'const std::vector<NodeConnection*>*' to 'std::vector<NodeConnection*>*' [-fpremissive]

How would I go about converting it to a constant pointer that I can return?

Upvotes: 0

Views: 1798

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

It's because GetConnections is marked as const but returns a non-const pointer.

Instead you should return either by value, const pointer, or (my advice) by const reference:

const std::vector<NodeConnection*>& GetConnections() const;

Making a member function const means that it will not (and is in fact disallowed from) change any object member variables. When you return a non-const pointer, the caller could possibly change the returned value which conflicts with the constness of the function.

The line causing the error is the return, when you return a const pointer and the compiler has to convert it to a non-const pointer.

Upvotes: 2

Related Questions