Reputation: 243
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.......
Upvotes: 0
Views: 2664
Reputation: 6240
Another solution would be to use a wrapper that is copyable
struct Reference
{
T* r_noncopyable_object;
};
Upvotes: 0
Reputation: 477650
Here's a version that works for non-constant references, too:
struct Bar { /* ... */ }:
struct Foo
{
Foo(Bar & br) : b(br) { }
Foo() : b(default_bar) { }
private:
static Bar default_bar;
Bar & b;
};
Bar Foo::default_bar;
This way, all default-constructed Foo
instances contain a reference to the common, static default_bar
object.
Upvotes: 2
Reputation: 88801
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.
Upvotes: 5