r/learncpp • u/Drekanoth • Sep 02 '21
Constructor with vector as parameters with default value
Hi,
So I'm having some trouble trying to implement a class "Movies_List" with holds a vector of objects of type "Movie" which has a constructor with default parameter(that is the problematic part). On the definition of the Movie_List class I have only defined a constructor with expects a vector of Movie but in case none is passed I have defined a default value.
The definition of the constructor looks like this on the .cpp file :
//Movies_List.cpp
Movies_List::Movies_List(const std::vector<Movie> &list = std::vector<Movie>())
:movie_list(list)
{
std::cout << "Arguments movie_list ctor << std::endl;
}
In my main.cpp file i just have the instation for the object:
//main.cpp
int main()
{
Movies_List my_list;
return 0;
}
When I try to compile this code i get an error that "No adequate constructor is provided".
To try to circumvent this I have implemented the following changes in the Movies_List class:
//Movies_List.h
#include <vector>
#include "Movie.h"
class Movies_List
{
private:
std::vector<Movie> movie_list;
public:
Movies_List();
Movies_List(const std::vector<Movie>&);
void add_movie();
};
And the .cpp file with both constructor like this:
#include "../Movies.h"
#include <iostream>
Movies::Movies()
:Movies(std::vector<Movie>{})
{
std::cout << "Empty movieS ctor\n" << std::endl;
}
Movies::Movies(const std::vector<Movie> &list = std::vector<Movie>())
:movie_list(list)
{
std::cout << "Argument movieS ctor\n" << std::endl;
}
With that the code compiles and runs as expected, but is there a way to implement it on the first way? Probably my error is the way that I defined the default parameter but i'm kinda stuck here, and although the second way works I would like to know how to do it the first way.
Thanks in advance.
View all comments
Show parent comment
1
u/Drekanoth Sep 02 '21
Thank so much, that fixed it! Can you explain me why it has to be in the declaration and not in the implementation?