-1

I have class hierarchy as shown below. It's a simplified version of actual code.

class Base
{
public :
   // user_define_type is a output parameter
   virtual void Fill(user_define_type);
}

class A : public Base
{
public :
    void Fill(user_define_type) override;
}
class B : public Base
{
public :
    void Fill(user_define_type) override;
}

I am overriding Fill() method as I need different formatting in both derived classes. Now I have to write one more class deriving from "Base" as it has common functionality. Now my problem is that new class will have to implement Fill() that will operate on different user defined type. As I am returning base class pointer from factory so new Fill() has to be virtual in base but that means I have to add it's definition in older classes "A" and "B" and throw not supported exception from them. This is not a good design. Any better design you guys can suggest ? Thanks in advance.

Anand Shah
  • 133
  • 10
  • There are a few options depending on what you're actually doing. Can you update your question with some actual code that shows what you're really trying to accomplish? – cdhowie Jul 07 '20 at 10:30

1 Answers1

0

I believe you need to create a common base class for your user_defined_types in order to achieve this. I also think this could be a good place to use the strategy pattern.

Basically, you create

class user_defined_type_base 
{
    ...
}

class user_defined_type_derived : public user_defined_type_base
{
    ...
}

class DoSomething
{
    private:
        DoSomethingStrategy *strategy;

    public:
        DoSomething(DoSomethingStrategy *strategy) { this->strategy = strategy; }
        void Fill(user_defined_type_base *type) { this->strategy->Fill(type); }
}

class DoSomethingStrategy
{
    public:
        virtual void Fill(user_defined_type_base *obj) = 0;
}

class DoSomethingStrategyA : public DoSomethingStrategy
{
    public:
        void Fill(user_defined_type_base *obj)
        {
            ...
        }
}

class DoSomethingStrategyB : public DoSomethingStrategy
{
    public:
        void Fill(user_defined_type_base *obj)
        {
            ...
        }
}

class DoSomethingStrategyC : public DoSomethingStrategy
{
    public:
        void Fill(user_defined_type_base *obj)
        {
            ...
        }
}

void main()
{
    DoSomethingStrategy *strategy = new DoSomethingStragegyA();
    DoSomething *dosomething = new DoSomething(strategy);
    user_defined_type_base *type = new user_defined_type_base();
    dosomething->Fill(type);

    DoSomethingStrategy *strategyC = new DoSomethingStragegyC();
    DoSomething *dosomethingC = new DoSomething(strategyC);
    user_defined_type_base *typeC = new user_defined_type_derived();
    dosomethingC->Fill(typeC);
}
buchipper
  • 606
  • 4
  • 16