Brett Holmes
Brett Holmes

Reputation: 387

How to make a dynamically allocated array that can hold derived objects in c++

Hello I'm doing a project for school that must use a dynamically allocated array of objects. I'm wondering where I went wrong on this one.

Mammal* Pets = new Mammal[arraysize]; Pets[count] = new Dog(tempweight, tempname)

There is an error that says no operator matches these operands for the second line of code.

Here is my constructor if that helps, and the Dog constructor.

Mammal::Mammal(void)
{
weight = 0;
name = "";
cout << "Invoking Mammal Default Constructor\n";
}

Mammal::Mammal(int tempweight, string tempname)
{
weight = tempweight;
name = tempname;
cout << "Invoking Mammal Constructor\n";
}

Dog::Dog(int tempweight, string tempname)
{
Setweight(tempweight);
Setname(tempname);
cout << "Invoking Dog Constructor\n";
}

Thank you,

Upvotes: 1

Views: 96

Answers (2)

user2848971
user2848971

Reputation:

You're trying to set a Dog* to a Mammal object. You have a pointer of Mammal objects. In this case you'll actually want an array of pointer to Mammal objects.

But don't do that. Use an std::vector of Mammal* at least:

std::vector<Mammal*> pets;

Or if you know the size and don't need to change it:

std::array<Mammal*, 10> pets;

Even better still:

std::vector<std::unique_ptr<Mammal>> pets;

Upvotes: 3

glampert
glampert

Reputation: 4421

You need to declare an array of pointers, like so:

Mammal ** Pets = new Mammal*[arraysize];

Upvotes: 3

Related Questions