Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ factory and casting issue

I have a project where I have a lot of related Info classes and I was considering putting up a hierarchy by having a AbstractInfo class and then a bunch of derived classes, overriding the implementations of AbstractInfo as necessary. However it turns out that in C++ using the AbstractInfo class to then create one of the derived objects is not that simple. (see this question, comment on last answer)

I was going to create like a factory class which creates an Info object and always returns an AbstractInfo object. I know from C# you can do that with interfaces, but in C++ things are a little different it seems.

Down casting becomes a complicated affair and it seems prone to error.

Does anyone have a better suggestion for my problem?

like image 686
Tony The Lion Avatar asked Feb 26 '26 20:02

Tony The Lion


1 Answers

You don't require downcasting. See this example:

class AbstractInfo
{
public:
    virtual ~AbstractInfo() {}
    virtual void f() = 0;
};

class ConcreteInfo1 : public AbstractInfo
{
public:
    void f()
    {
        cout<<"Info1::f()\n";
    }
};

class ConcreteInfo2 : public AbstractInfo
{
public:
    void f()
    {
        cout<<"Info2::f()\n";
    }
};

AbstractInfo* createInfo(int id)
{
    AbstractInfo* pInfo = NULL;
    switch(id)
    {
    case 1:
        pInfo = new ConcreteInfo1;
        break;

    case 2:
    default:
        pInfo = new ConcreteInfo2;
    }

    return pInfo;
}


int main()
{

    AbstractInfo* pInfo = createInfo(1);
    pInfo->f();
    return 0;
}
like image 53
Naveen Avatar answered Mar 01 '26 08:03

Naveen



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!