I would like to implement several constructors for my class via overloading. As I understand the way to do this idiomatically, following the DRY principle, is using a feature called delegating constructors. I also have seen thoughts about using reference parameters everywhere and avoiding pointers at all cost because references is a c++ way etc.
So here is how I see this could be implemented with pointers (which works):
class B {};
class C {};
class A {
public:
A();
A(const B* b);
A(const B* b, const C* c);
private:
const B* b_;
const C* c_;
};
// These ctors short and concise, delegating work to last ctor
A::A() : A(nullptr, nullptr) {}
A::A(const B* b) : A(b, nullptr) {}
// This ctor contains code that deals with b or c being nullptr
// Ideally I only modify code in this ctor (DRY)
A::A(const B* b, const C* c) : b_(b), c_(c) {
//code
}
The following, obviously, doesn't work:
class B {};
class C {};
class A {
public:
A();
A(const B& b);
A(const B& b, const C& c);
private:
const B& b_;
const C& c_;
};
A::A() : A(nullptr, nullptr) {}
A::A(const B& b) : A(b, nullptr) {}
A::A(const B& b, const C& c) : b_(b), c_(c) {
//code
}
So the question is how to implement delegating constructors following semantics in a pointer example but with reference as constructor's parameters.
(Do I totally miss the point here somewhere? Maybe even staring with the overall idea?)