Is there any way to avoid code replication across different constructors of a class?
class sample
{
int a, b;
char *c;
public:
sample(int q) :
a(0),
b(0),
c(new char [10 * q])
{
}
sample() :
a(0),
b(0),
c(new char [10])
{
}
}
It's called a delegating constructor. In your case it would look like this:
sample(int q) : sample(q, 10 * q)
{
}
sample() : sample(0, 10)
{
}
sample(int q, int d) : a(q),
b(q),
c(new char [d])
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With