dimanche 15 mars 2020

A function to return different derived-type object/reference not a pointer [duplicate]

How to create a function returning a derived-object/reference? I have this code that uses the covariance method. However, I prefer the return to be an object, not a pointer.

What I have and it's working fine.

class Base {    
    protected:
        Base(){};
    public:
        virtual ~Base(){};
        virtual void print() = 0;
};

class Derived1 : public Base 
{
    public:
        Derived1() : Base() {};
        ~Derived1() {};
        void print() override { std::cout << "Derived1" << std::endl;}
};

class Derived2 : public Base
{
    public:
        Derived2() : Base() {};
        ~Derived2() {};
        void print() override { std::cout << "Derived2" << std::endl;}
};


std::unique_ptr<Base> getDerived(int t)
{
    if (t == 2)
        return std::make_unique<Derived2>();
    // default
    return std::make_unique<Derived1>();
}

int main()
{
    auto d1_p = getDerived(1);
    auto d2_p = getDerived(2);
    d1_p->print(); // "Derived1"
    d2_p->print(); // "Derived2"
    return 0;
}

The above code works fine and prints out "Derived1" and "Derived2" correctly.

However, I would like to get an object than a pointer. Ideally, this should work.

int main()
{
    auto d1_p = getDerived(1);
    auto d2_p = getDerived(2);
    d1_p.print(); // "Derived1"  
    d2_p.print(); // "Derived2"
    return 0
}

Are there any workaround?

Aucun commentaire:

Enregistrer un commentaire