a concerned citizen a concerned citizen - 3 months ago 7
C++ Question

C++ Instantiate, inside another class, a class-type variable from a group of classes with same constructor

I am not advanced in C++. Suppose I have a group of classes, from

A
to whatever (the number will grow in time), that use the same type of constructor. Suppose it looks like this:

class A
{
private:
double m_x, m_y;
public:
A(const double &x, double &y, const short &n) { ... };
};


Each of these classes have the same
m_x, m_y
variables, but they calculate it differently. Now there's another class, say
Bla
, who needs to use the constructors from the previous group of classes, something like this:

class Bla
{
private:
Class m_class;
public:
Bla(const double &x, const double &y, const double &z, const short &i)
{
switch (i)
{
case 1: m_class = A::A(...); break;
case 2: m_class = B::B(...); break;
...
}
}
};


The
switch (i)
in the constructor chooses one of the group's constructor according to
i
. How can I make the
Class m_class
variable inside
Bla
to be consistent with the
switch (i)
in the constructor? What type of variable should I choose, or how?

Alternatively,
m_class
only needs to hold the
m_x, m_y
variables coming from one of the classes in the group, to be further processed/calculated/etc, is there another method of doing this? I hope I managed to be clear about this.

Answer

You could have an interface class with those common member variables

class I
{
public:
    virtual ~I() = default;
protected:
    double m_x, m_y;
};

Then derive your concrete classes from that, each of which will populate m_x and m_y differently.

class A : public I
{
public:
    A(const double &x, double &y, const short &n) { ... };
};

Then your Bla constructor essentially acts as a factory and makes specific types of I depending on your i parameter

class Bla
{
private:
    std::unique_ptr<I> m_class;
public:
    Bla(const double &x, const double &y, const double &z, const short &i)
    {
        switch (i)
        {
        case 1: m_class = std::unique_ptr<I>(new A(...)); break;
        case 2: m_class = std::unique_ptr<I>(new B(...)); break;
        ...
        }
    }
};
Comments