The error message is telling you that the class AAA
does not have a default constructor. That is required because new
will default-construct each element in buffer
.
The only constructor AAA
provides right now needs an integer parameter that's used to construct the object with an ID.
It's up to you what you choose to do here. By far the simplest fix is to relax that constructor and provide a default id
if none was specified. This conveniently gives you a default constructor by magic.
class AAA {
private:
int id;
public:
AAA(int s = 0) : id(s) {}
};
As a side-node, your main
definition is wrong. It needs parentheses:
int main()
{
Buffer<AAA> buffer(3);
}
Don't forget about The Rule of Three for your Buffer
class. Right now, it leaks memory and is unsafe to copy. Consider using std::vector
instead of allocating data yourself. At the very least, avoid storing raw pointers: use std::unique_ptr<T[]>
instead.
As pointed out by Davis Herring in the comments, your class might intentionally have no valid default / empty state. In that case, std::vector
is really what you need. Here's your Buffer class adjusted to reserve vector storage instead.
template<typename T>
class Buffer {
private:
std::vector<T> buffer;
public:
Buffer(int capacity)
{
buffer.reserve(capacity);
}
void Add(const T & val)
{
buffer.push_back(val);
}
void Add(T && val)
{
buffer.push_back(std::move(val));
}
};
Note that the vector is still empty, but has reserved storage. You will need to create method(s) in the Buffer
class to append stuff to it, as suggested in the example.