Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to avoid code replication across different constructors of a class?

Tags:

c++

c++11

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])
    {
    }
}
like image 313
Anoop pS Avatar asked Jul 28 '16 11:07

Anoop pS


1 Answers

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])
{
}
like image 103
Sam Varshavchik Avatar answered Oct 01 '22 13:10

Sam Varshavchik