mardi 5 juillet 2022

Factory pattern for stack allocated objects in c++ [duplicate]

I'm a beginner c++ programmer and I would like to know whether it is possible to create stack-allocated objects with a factory design pattern like in this code.

'''

class IInterface {
public:
    virtual ~IInterface() = default;
};

class Car : public IInterface
{
public:
    Car()
    {
        std::cout << "Car Created with Value " << this->x << std::endl;
    }
    ~Car()
    {
        std::cout << "Car Destructed" << std::endl;
    }
public:
    size_t x = 6;
};

class Bus : public IInterface
{
public:
    Bus()
    {
        std::cout << "Bus Created with Value " << this->x << std::endl;
    }
    ~Bus()
    {
        std::cout << "Bus Destructed" << std::endl;
    }
public:
    size_t x = 9;
};

IInterface Factory(int random = 0)
{
    if (random == 1)
    {
        Bus b;
        return b;
    }
    Car c;
    return c;
}

int main()
{
    IInterface I = Factory(1);
}

'''

If this is correct, I would like to know stack object inside the Factory() function gets copied to the main() function, and am I able to dynamic cast to an appropriate derived cast later to get the data members?

Aucun commentaire:

Enregistrer un commentaire