Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Calling a base class constructor with a computed argument

This simple example demonstrates the C++ syntax for calling base class constructors - as far as I understand it as a C++ learner:

class BaseClass {
protected:
  int i;
public:
  BaseClass(int x) { 
     i = x; 
  }
};

class DerivedClass: public BaseClass {
  int j;
public:
  DerivedClass(int x, int y): BaseClass(y) { 
     j = x; 
  }

Here, the base class constructor can take named arguments to the derived class constructor as input.

Now, what if I want to call BaseClass() constructor with an input value that is not a direct input to DerivedClass()? Basically, I'd like to do some multiline work with x and y within DerivedClass(), then pass a calculated value to BaseClass(). Can this be done with constructors? Should this be done with some kind of initializer method instead?

like image 434
clstaudt Avatar asked Apr 21 '12 16:04

clstaudt


2 Answers

You can do that, yes:

class BaseClass
{
  public:
    BaseClass(int x) : i(x) {}

  private:
    int i;
};

class DerivedClass: public BaseClass
{
  public:
    DerivedClass(int x, int y):
      BaseClass(compute(x, y)), // Neither i or j are initialized here yet
      j(x)
      {}

  private:
    static int compute(int a, int b) { return a + b; } // Or whatever
    int j;
};

Note that you can even make compute() a non-static method but be aware that DerivedClass or BaseClass members won't be initialized at the time of the call. So you won't be able to rely on their values.

like image 118
ereOn Avatar answered Oct 06 '22 20:10

ereOn


If you're using C++11 or newer you can also use lambda expressions:

class BaseClass
{
  public:
    BaseClass(int x) : i(x) {}

  private:
    int i;
};

class DerivedClass: public BaseClass
{
  public:
      DerivedClass(int x, int y): BaseClass(
          [=]()->int
            {
                int sum = 0;
                for(int i = 0; i < x; ++i)
                {
                    sum += y + i * x;
                }
                return sum;
            }()), j(x)
      {}

  private:
    int j;
};
like image 41
helloworld922 Avatar answered Oct 06 '22 21:10

helloworld922