1
class Zombie { public: Zombie(); Zombie(int howTall); Zombie(int howTall, int howHeavy); int getHeight(); private: int height; int weight; }; Zombie::Zombie() { height = 6; weight = 180; } int main() { Zombie army[4]; for(int i = 0; i < 4; i++) army[i] = Zombie; } 

Why do I get the error when I try to set army[i] = Zombie? Army is an array of Zombies and I already wrote a default constructor for the Zombie class. when I replace Zombie with Zombie(), the code works, but shouldn't omitting the () call the default constructor as well?

Not shown: the other constructors and methods are implemented already.

I know that if I declare army to be an array of pointers to Zombies and do army[i] = new Zombie it will work, but I don't know why the above code doesn't.

Thanks

2 Answers 2

2

When you do:

Zombie army[4]; 

You are already constructing 4 Zombies of height 6 and weight 180. The default constructor is being called 4 times (try to add a call to std::cout in it and you'll see!).

Therefore what you are attempting to do in your loop is not needed, unless you want (for whatever reason), to construct new zombies again. In which case, the proper syntax would be:

army[i] = Zombie(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, random downvotes with no explanation, you make my day. throws a rock at some innocent bypasser for no reason
Naw, you're purrfect.
0

Because you're trying to assign a type and not an object of that type.

Besides that you have already the objects in army, you would only need to assign a new object now, when you want to overwrite the values with 'new Zombies'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.