Joy
Joy

Reputation: 1777

passing a vector parameter empty

I have been using this class :

class DogTrainer 
{
    public:
        DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz) :    
         idD(identity),
         name(nom),
         trainees(dogz)
    { };

        ~DogTrainer();

    private:
        int idD;
        string name;
        std::vector<Dog*> trainees;
};

but sometimes when I want to instantiate a new object, I don't need to pass a "trainees" parameter, so I want to have the possiblity to do this

DogTrainer* Trainer=new DogTrainer(my_id, my_name);

therefore I tried to change in my DogTrainer constructor

DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz="") :
    idD(identity), 
    name(nom), 
    trainees(dogz)
{ };

but it didn't work so any help please !

Upvotes: 1

Views: 5296

Answers (2)

Boris Strandjev
Boris Strandjev

Reputation: 46943

It will not work because you are trying to assign empty string to a vector. Just overload the constructor omitting the last parameter.

DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz)
    :idD(identity), name(nom), trainees(dogz) {
};

DogTrainer(int identity,const std::string& nom):idD(identity), name(nom) {
};

This will virtually be the same from user perspective to what you want to achieve.

Upvotes: 1

jamesdlin
jamesdlin

Reputation: 89965

Declare your constructor as:

DogTrainer(int identity,const std::string& nom,
           const std::vector<Dog*> dogz = std::vector<Dog*>());

"" is a const char*, and a std::vector is not constructible from that.

Incidentally, there's not much point in dogz being a const std::vector<Dog*>. Either make it non-const or make it a const reference.

Upvotes: 3

Related Questions