J
jrwats
So at my work, people are morally opposed to default arguments and
prefer function overloading. Put your opinions about that aside for
the moment (because I don't have a choice but to bow down to coding
standard)
Problem is if class B inherits from class A, which provides no default
constructor, how can you effectively provide an overloaded
constructor?
This following does not work:
class A {
public:
A(int x) { }
};
class B : A {
public:
B(int x, int y) : A(x) { }
B(int x) { B(x,20); } // error: no matching function for call to
A::A()
};
Neither does this:
class B : A {
public:
B(int x, int y) : A(x) { }
B(int x) : B(x,20) { } // type 'B' is not a direct base of 'B'
};
This following works, but I really do not like it:
class B : A {
public:
B(int x, int y) : A(x), m_nX(x), m_nY(y) { }
B(int x) : A(x), m_nX(x), m_nY(20) { }
int m_nX;
int m_nY;
};
If we want different behavior in the constructor, we have to change it
in both places. Blech!
prefer function overloading. Put your opinions about that aside for
the moment (because I don't have a choice but to bow down to coding
standard)
Problem is if class B inherits from class A, which provides no default
constructor, how can you effectively provide an overloaded
constructor?
This following does not work:
class A {
public:
A(int x) { }
};
class B : A {
public:
B(int x, int y) : A(x) { }
B(int x) { B(x,20); } // error: no matching function for call to
A::A()
};
Neither does this:
class B : A {
public:
B(int x, int y) : A(x) { }
B(int x) : B(x,20) { } // type 'B' is not a direct base of 'B'
};
This following works, but I really do not like it:
class B : A {
public:
B(int x, int y) : A(x), m_nX(x), m_nY(y) { }
B(int x) : A(x), m_nX(x), m_nY(20) { }
int m_nX;
int m_nY;
};
If we want different behavior in the constructor, we have to change it
in both places. Blech!