Struggling to understand C++ template instantiation

Viewed 65

I am writing a template class, and then need to write test cases to test my code and verify all of the methods work properly. In my testing file, I attempt to create an instance of Collection, but get the following error: "no instance of constructor "Collection" matches the argument listC/C++(289)". I have a no-arg constructor defined, so I am not sure why it is not working.

Here is the portion of my class where I define the constructor:

    template <typename Object>
class Collection
{
    // TODO(student): the rest of the template
private:
    Object *objectsArr;
    int maxArrSize = 10;
    int sizeOfCollection = 0;

public:
    Collection()
    {
        objectsArr = new Object[maxArrSize];
    }
    

and in the test file, I try to instantiate the Collection with:

Collection<int> testCollection = new Collection();

This is where i get the error message: "no instance of constructor "Collection" matches the argument listC/C++(289)".

Can someone help me understand why I am receiving this error message?

2 Answers

The operator new returns a pointer.

So this declaration

Collection<int> testCollection = new Collection<int>();

(where you forgot to specify the template argument in the expression with the operator new) can be imagined the following way

Collection<int> *p = new Collection<int>();
Collection<int> testCollection = p;

And the compiler tries to find a constructor that is declared like

Collection<int>( Collection<int> * );

because you are initializing an object of the type Collection<int> with a pointer returned by the operator new.

But the class does not have such a constructor with one parameter.

You have to write

Collection<int> *testCollection = new Collection<int>();

You are missing the asterisk indicating a pointer type and the template argument when instantiating. The correct code is

Collection<int> *testCollection = new Collection<int>();

The new operator returns a pointer to the type that it allocates in the heap memory, hence the asterisk indicating a pointer type.

We also have to indicate the template type we want to instantiate with in new Collection<int>() so that the compiler knows how much memory to reserve for your object.

For future reference, using smart pointers such as std::unique_ptr is considered better practice. If this confuses you, you can ignore it for now.

Related