Braden Best Braden Best - 2 months ago 6
C++ Question

How to call constructor of a nested class

First off, I'm not talking about questions like these (1, 2). I'm talking about a class that already has a constructor and is only nested by value, not by definition...if that makes any sense.

Currently, I have this methodology, which works, but uses

new
and is ugly IMO:

class A {
private:
int value;

public:
A(int _value);
};

class B {
private:
A *a;
public:
B(int _value);
};


The constructor of B:

B::B(int _value)
{
a = new A(_value);
}


If I were to change
A *a;
to
A a
, how would I create a
B
such that
A
's constructor is called in the same way?

I've tried:

B::B(int _value)
{
a = A(_value); // no matching function for call to ‘A::A()’
a = A::A(_value); // cannot call constructor ‘A::A’ directly
a(_value); // no match for call to ‘(A) (int&)’
a.A(_value); // invalid use of `A::A`
}


It doesn't seem possible without:


  • using a pointer with
    new

  • using some explicit
    void A::init(_value)
    (would need an additional constructor for
    A
    to take no arguments)

  • extending class A (would require changing specific private members to protected and would mesh their "namespaces" in an unwanted manner)

  • questionable use of
    memcpy()
    (
    A temp(_value); memcpy(&a, &temp, sizeof (A));
    )



Is this possible without resorting to the above methods?

Answer

You use initialisation lists.

I.e. B constructor looks like

class B {
   ...

   A a;
};

B::B(int _value) : a(_value) {
  ...
}
Comments