0

I am encountering a problem that I am sure is small but when I try to run my program it states - push_back(T &):cannot convert argument 1 from 'Savings*' (or Checkings*) to 'Account *&.

It works if I remove & from the push_back parameter but I don't understand what the difference is when you try to pass by reference rather than copy. Shouldn't it work the same?
I have attached the code where the error begins in the source.cpp file and the push_back function in MyVector.h.

source.cpp:

MyVector<Account*> acc;

acc.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
acc.push_back(new Checkings(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
acc.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));

MyVector.h:

template<class T>
void MyVector<T>::push_back(T& n)
{
    if (vCapacity == 0)
    {
        vCapacity++;
        T* tmp = new T[vCapacity];
        delete[] vArray;
        vArray = tmp;
    }

    if (vSize >= vCapacity)
    {
        grow();
    }
    vArray[vSize] = n;
    vSize++;
}
tux3
  • 7,171
  • 6
  • 39
  • 51
greg-mora
  • 29
  • 5

1 Answers1

3

Assuming Savings and Checkings are derived from Accounts, passing by reference doesn't work since you cannot bind a temporary to a non-const reference.

Change the signature to

template<class T>
void MyVector<T>::push_back(const T& n)

Passing by value works, since you effectively copy the argument.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • @juanchopanza edited, realized now that OP is passing actually pointers. The answer is still ok, since the same applies to pointer temporaries trying to bind to references to pointers. – vsoftco Apr 12 '15 at 21:23
  • Since you're storing by value, you can't avoid slicing. However, slicing of pointers is not a problem. – Ben Voigt Apr 12 '15 at 21:23
  • Not really that odd, `std::vector` is a good way to store a polymorphic collection of objects (`std::vector>` would be even better), and this looks like a homegrown version (hopefully for learning purposes) – Ben Voigt Apr 12 '15 at 21:28