jeudi 18 juin 2020

Have a trivial constructor in class derived from one without trival constructor

Suppose I am using a class that was IMO badly designed and it doesn't have a default trivial constructor.

class cx{ // legacy class
protected:
   double rl;
   double ig;
public:
   cx() : rl{0.}, iq{0.}{} // this constructor is not trivial
   cx(double rl, double ig) : rl{rl}, ig{ig}{}
};

Is it possible to derive from that class but have a default trivial constructor?

class zx : public cx{ // new class
    zx() = default; // this doesn't make the constructor trivial
//  zx(){} // this neither
};

The problem is that all the constructors of zx (derived from cx) call some constructor of the base class, and none of them is itself trivial. I know this is a subversion of the intent of the original design of the class, so I am willing to play with UB if necessary.

The closest to a solution I found is to hold a buffer but then I cannot use inheritance. And it is horrible.

class zx{
   char buffer[sizeof(cx)];
   zx() = default;
   zx(double rl, double ig){new (buffer) cx(rl, ig);}
   ... overload all operators so that zx behaves like cx
}

Aucun commentaire:

Enregistrer un commentaire