Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have been trying to pass object of an abstract class as by reference but it clearly gives error when I try to store this objects in an array of pointers with the same data type. Can anyone please explain what I'm doing wrong? It's in the following function:

    void enterItem(DessertItem& item) 
    {
        if (top != (maxSize-1))
        {
            arr[top] = &item;
            top++;
        }
    }

The dessertItem class is actually an abstract class and "arr" is a pointer array of dessertItem so it can give reference to any new object whenever it gets passed by reference. I can't get it how am I supposed to do that? Here's the class:

    class Checkout

    {

        ////Maintains a list of DessertItem references.
        protected:

        int maxSize;

        int top;

        DessertItem **arr;


    public:

    Checkout()

     {

    ///Creates a Checkout instance with an empty list of DessertItem's 


         this->maxSize=5;
         this->top=0;
         this->arr = new DessertItem*[maxSize];
         for(int i=0; i<maxSize; i++)
         {
             arr[i]=NULL;
         }
     }


     ////Clears the Checkout to begin checking out a new set of items 
    void clear()

    {

        for(int i=0; i<maxSize; i++)
         {
             arr[i]=NULL;
         }
    }


    //A DessertItem is added to the end of the list of items

    void enterItem(DessertItem &item) 

    {

        if(top!=(maxSize-1))


        {
            arr[top]=&item;
            top++;
        }
    }


     //Returns the number of DessertItem's in the list 


    int numberOfItems()

    {

        return this->top;
    }

    };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

store your abstract objects in a vector<unique_ptr<T>>. when you construct them, construct them as unique_ptr, eg:

class Base {
public:
  virtual ~Base() = default;
  virtual void method() = 0;
};

class Impl : public Base {
public:
    void method() override { /* perform action here */ };
};

create and store like so:

// nasty old c-style array
std::unique_ptr<Base> a[10];
a[0] = std::move(std::unique_ptr<Base>(new Impl));

// std::vector 
std::unique_ptr<Base> p { new Impl };
std::vector<std::unique_ptr<Base>> v;

v.push_back(std::move(p));
// or
v.emplace_back(new Impl);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...