Akiiino
Akiiino

Reputation: 1090

How to use `const`ness in this example?

I have some code which implements graph algorithms; in particular, there are these snippets, which cause problems:

class Path{
private:
    const Graph* graph;

public:
    Path(Graph* graph_) : graph(graph_) {
        ...
    }

(which is supposed to create Path object with a constant pointer to a graph)

class GradientDescent{
private:
    const Graph graph;
public:
    Path currentPath;
    GradientDescent(const Graph& graph_) : graph(graph_), currentPath(Path(&graph_)) {}

(which is supposed to create a GradientDescent object that has a const Graph and a non-const Path)

The problem is, as I am just trying to figure out how to use consts, I get this error:

error: no matching constructor for initialization of 'Path'
    GradientDescent(const Graph& graph_) : graph(graph_), currentPath(Path(&graph_)) {}

longest_path.cpp:103:9: note: candidate constructor not viable: 1st argument ('const Graph *') would lose const qualifier
    Path(Graph* graph_) : graph(graph_) {

Upvotes: 1

Views: 430

Answers (1)

krzaq
krzaq

Reputation: 16421

The problem is that your Path's constructor expects a pointer to non-const Graph.

To get rid of this problem simply change your constructor declaration:

Path(const Graph* graph_) : graph(graph_) {
    ...
}

Upvotes: 1

Related Questions