Akiiino Akiiino - 1 month ago 7
C++ Question

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
const
s, 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_) {

Answer

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_) {
    ...
}