Class system architecture in C ++

Viewed 64

For my latest project I have a class

class Parent {
    public:
        // class constructor
        Parent();
        
        // member function
        double fun(double x)
};

and another class

class Child {
    private:
        int type;
    public:
        // class constructor
        Child(int itype);
};

I know that I can inherit the functions from Parent by specifying class Child : public Parent so that instances of my class child can call fun. However, I want that the function fun perform different computations depending on type. For instance, if an instance of my Child class was initialized by Child nChild(1); the call nChild.fun(5) should return the square root of 5, while initializing the class by Child nChild(2); the call nChild.fun(5) should return the logarithm of 5 and so on.

How could I design a system of classes with dependencies such that the function in the parent class depends on the value of the child class? Does this even make sense or is or is generally advised against such a architecture? Note that I am not a C++ expert.

1 Answers

You could keep a protected: int myType; in the parent class and use that in the derived class to switch on. However the better design is to make a diffrent derived class for each type that would override the fun() method.

class Parent
{
public:

    Parent();

    virtual double fun(double x) = 0;
};

class ChildLog : public Parent
{
public:
    ChildLog();
    double fun(double x)
    {
        // return log(x)
    }
};

class ChildSqrt : public Parent
{
public:
    ChildSqrt();
    double fun(double x)
    {
        // return sqrt(x)
    }
};
Related