Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good methods to return pointers pointing to subclass [closed]

Tags:

c++

Here is a design challenge I have to deal with. Sub-class of Base has it's own specific functions that are NOT defined in the Base. I need to design a method so that I can generate different instance of subclass based on the input date.

The input data Data as the pass-in parameter of function FactoryMethod contains some complicated logic that determines which subclass is to be generated. The problem of pre-existing design(i.e. FactoryMethod listed as below) is that clients have to downcast the return pointer pointing to base in order to call the functions defined solely in subclass. This method is problematic b/c in the current design, we don't know what subclass is created inside the FactoryMethod. I can only think about two potential solutions

Solution 1> introduce a type in the base which stores the type information of the pointer pointing to base. Is there a good example that shows me the best practice?

Solution 2> return pointers pointing to subclasses instead of base in the implementation of FactoryMethod. Again, is there a good example to show off this?

class Base {
public:
    ...
    virtual void BaseFuncA() {}
};

class SubClassA : public Base {
public:
    ...
    void SubClass_A_Func2() {}
}

class SubClassB : public Base {
public:
    ...
    void SubClass_B_Func3() {}
}


Base* FactoryMethod(Data)
{
    if (Data designed for SubClassA)
        return new SubClassA

    if (Data designed for SubClassB)
        return new SubClassB
    ...    
}

Problems: Clients of SubClassA has to downcast in order to call subclass function

SubClassA* ptr = dynamic_cast<SubClassA*> (pointer to Base*);

As we all know, if you always have to deal with downcast in your code then the design has a flaw.

Question> Is there a good book/resource where I can find a practical solution for this problem. In other words, the client of the code doesn't have to downcast the pointer in order to use the functions defined in subclass. For example, the factory method may return the subclass pointer instead by adopting boost::variant?

BTW: It is not realistic to put all functions into Base and provide dummy implementation in the Base. Even if you can do so, you will not be able to get real functionality provided by subclass without downcast.

like image 890
q0987 Avatar asked Jan 01 '26 00:01

q0987


1 Answers

Try to read about visitor pattern to avoid down class cast. Hope it helps.

http://en.wikipedia.org/wiki/Visitor_pattern

like image 187
Dmitriy Kachko Avatar answered Jan 02 '26 12:01

Dmitriy Kachko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!