so I've made a class in c++ which has 2 reference type members:
class Edge{
private:
const Node& base;
const Node& target;
public:
Edge(const Node& new1, const Node& new2);
I want to give default values to base and target in the C'tor. Which means that:
Edge()
will not be an error, but will do create an Edge object. How do I do that?
edit: I'm also trying to do:
Edge::Edge(const Node& newBase, const Node& newTarg)
{
m_base=newBase;
m_target=newTarg;
}
But it won't let me, it says no operator "=" matches this operators. But I did make a "=" operator for Nodes and checked it worked.......
You can give new1
and new2
defaults like any other parameter. The trick is that since they're passed by reference and (presumably) you're using them to set base
and target
they need to live long enough for this to make sense. You can do that by making a static "dummy" Node
to use as the default for where one hasn't been specified, e.g.:
class Node {};
class Edge{
private:
static const Node none;
const Node& base;
const Node& target;
public:
Edge(const Node& new1=none, const Node& new2=none) : base(new1), target(new2) {}
};
const Node Edge::none;
int main() {
Edge e;
}
If that's good design or not is another issue though. There might well be a smarter solution to the underlying problem that you're trying to solve.