-2

There is non-pointer (body) nested class in outer class.I need to call its constructor from outer class constructor after some calculations.How to do?

class nested
{
  int value;
  nested(int x) {value=x;};
  nested() {value=0;};
};
class outer:
{
  nested n;
  nested *pn; 
  outer(int x);
};
outer::outer(int x1)
{
  x = x1;
  y = x + 1 *x*x;//some long calculations needed for nested
  pn = new nested(y); //this is trivial
  n = nested(y); //??? how to initialize non-pointer class?????
}
  • Btw you can just do `nested(int x = 0) { value = x; }` and remove the no-arg constructor. – Emil Laine Feb 15 '16 at 16:35
  • 1
    Possible duplicate of [Explicitly initialize member which does not have a default constructor](http://stackoverflow.com/questions/31488756/explicitly-initialize-member-which-does-not-have-a-default-constructor) – Tadeusz Kopec for Ukraine Feb 15 '16 at 16:45
  • @TadeuszKopec Here `nested` has a default constructor. – Emil Laine Feb 15 '16 at 16:53
  • @zenith Still question boils down to "How to provide a parameter to custom constructor of member" and it is present in zilion of instances on SO. If you are aware of a canonical question about it, please show it. – Tadeusz Kopec for Ukraine Feb 16 '16 at 09:28

1 Answers1

1

One solution would be to calculate y and store it as a member variable. That way you can calculate and cache it before initializing anything that depends on it.

class outer
{
public:
    outer(int x)
        , y(CalculateY(x))
        , n(y)
        , pn(new nested(y))
    {}

private:
    int CalculateY(int x); // this can be static

    int y;    
    nested n;
    nested *pn;
};

Note

int y must be declared before anything that relies on it since member variables are initialized in the order they're declared in.

Mohamad Elghawi
  • 2,071
  • 10
  • 14