0

Im trying to create 2 vectors of 5 objects (Cats) with a constructor parameter (color).

But i cant find the right syntax.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

class Cats{
Cats(string color);

};

Cats::Cats(string color){
cout << "Cat " << color << " created" << endl;
}

int main()
{
  vector<Cats> blacks (5, "black");
  vector<Cats> whites (5, "white");
}

I want the string of each cat with the color i write to the constructor.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Pablo Lopez
  • 67
  • 2
  • 9

2 Answers2

2

You want vector<Cats> blacks(5, Cats("black"));.

Also see Why should I not #include <bits/stdc++.h>?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
2

The compiler will not automatically perform two implicit conversions. Your string literal is a const char* which needs to be converted to std::string and then to Cats before it is the correct type to pass into the vector constructor.

You can help the compiler out by performing one of the conversions explicitly:

// Pass Cats to the vector constructor, compiler implicitly converts string literal to std::string
vector<Cats> blacks(5, Cats("black"));
// Pass std::string, compiler implicitly converts to Cats before calling the vector constructor
vector<Cats> whites(5, std::string("black"));

Alternatively if you're going to be calling code similar to this often, it could be simpler to add a const char* constructor to Cats:

class Cats{
Cats(string color);
Cats(const char* color)
:Cats(std::string(color))
{}
};

Your original code would then work.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60