0

I have a class which I want to hold an abstract class object.

class myClass
{
abstractClass abstractObject; //won't work since abstractClass is abstract
// ....
}

where abstractClass is an abstract base class. Then I might have a non-abstract derivedClass1 and derivedClass2, both of which inherit from abstractClass. I want to pass these derived class into myClass. How do I do this using rvalues?

I want to be able to e.g. say

myClass someOBJ(derivedClass1(x, y, z));
myClass someOtherOBJ(derivedClass2(x,y,z));

and then these two objects now hold objects of type derivedClass1 and derivedClass2.

jenbo5
  • 51
  • 2
  • What's the problem? Are you trying to write constructors of myClass that accept objects of these derived classes? – PlinyTheElder Sep 21 '18 at 18:37
  • Yes, but I don't want to have to create the objects outside the class and then pass them in. I want to create them simultaneously like an rvalue. – jenbo5 Sep 21 '18 at 18:45
  • You should use the pointer of the abstract class. – tunglt Sep 21 '18 at 19:04

2 Answers2

0

maybe you should use a pointer pointing to the object like abstractClass* ptr; and write a constructor accepting rvalues like myclass::myclass(abstractClass&& rval)

Einiemand
  • 302
  • 1
  • 8
0

If you want to retain polymorphism, you will need to use either a pointer or a reference to abstractClass in myClass.

The proper C++ was to accomplish this is by using std::unique_ptr<>:

#include <memory>

class AbstractClass
{
public:
    virtual void func() = 0;
};


class DerivedClass : public AbstractClass
{
public:
    void func() {};
};


class myClass
{
    std::unique_ptr<AbstractClass> ptr;

public:
    myClass(AbstractClass* p) : ptr(p) {}
};


int main()
{
    myClass(new DerivedClass());

    return 0;

    //myClass will automatically call delete on the pointer
}
PlinyTheElder
  • 1,454
  • 1
  • 10
  • 15