1

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,

0

2 Answers 2

3

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

Mammal ** Pets = new Mammal*[arraysize];
Sign up to request clarification or add additional context in comments.

Comments

3

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;

7 Comments

And by at least, you of course mean a vector of smart pointers :)
Yeah, that'd be the best way to go about it.
I would use vector, but I don't exactly know how to do that in this class so I think it'd be best to go with glampert's code. Thanks though!
@BrettHolmes Not knowing how to use a language feature / library is an excuse to write bad code?
@BrettHolmes, For the most part, you can use these the exact same way as an array or pointer apart from the declaration, but no need to clean up, and no need to worry about an exception happening and causing a lack of cleanup.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.