0

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?

Pasan
  • 1
  • Something like this would work in Java, but C++ is not Java. More focus on a good textbook, less focus on "design patterns" and the rest of the buzzword bingo. No, it doesn't get copied, and a dynamic cast will reward you with a `nullptr`. – Sam Varshavchik Jul 06 '22 at 01:08
  • As you've done it, no. Firstly, `IInterface` is an abstract (non-instantiable) class, so cannot be returned by value. If that is addressed, returning objects by value would result in object slicing. Returning a pointer (or reference) would avoid slicing, but cause undefined behaviour if objects of automatic storage duration are returned (since the function would return a pointer/reference to an object that no longer exists). That could be addressed if your objects had `static` storage duration - but that imposes other disadvantages. – Peter Jul 06 '22 at 01:16
  • This `IInterface` is perfectly instantiable, but that's besides the point... – Sam Varshavchik Jul 06 '22 at 01:26
  • @Peter and SamVarshavchik thank you for your comments. If I modify Factory function like this -> IInterface& Factory(int random = 0); and modify the code in the main like this IInterface& I = Factory(1); Bus& d = dynamic_cast(I); will this work? (if so, Why the stack-allocated object in the Factory function returned by reference to the main function does not get nullified or deallocated once we leave the Factory function?) – Pasan Jul 06 '22 at 03:51

0 Answers0