In my class, I have two vector objects:
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
I also have the following function:
std::vector<std::string> & get_vecteur_noms_A_() {
return vecteur_noms_A_;
}
but I do not have the same for the B
one!
When I instantiate my class, and do the following instructions in my class constructor; I can see (via debugging or when It throws an error) that:
vecteur_noms_A_.push_back("some value"); // is ok
vecteur_noms_B_.push_back("some other value"); // is not ok <- throws an error.
Debugging let me see that an object (or instance ?)(empty vector) is existing for vecteur_noms_A_
but not for vecteur_noms_B_
.
It is not clear why I observe that comportment I did not expect, I would be happy if I get an explanation.
Does the fact that I define a function forces the compiler to instanciate the object?
Here is an example :
#include <iostream>
#include <vector>
using namespace std;
class GP
{
public:
//Constructeur
GP(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B
);
//Fonctions
void construction_vecteur_A_B_(std::vector<std::string> list_names_A, std::vector<std::string> list_names_B);
std::vector<std::string>& get_vecteur_noms_A() {
return vecteur_noms_A_;
}
std::vector<std::string> vecteur_noms_A_;
std::vector<std::string> vecteur_noms_B_;
};
GP::GP(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b) {
construction_vecteur_A_B_(list_names_a, list_names_b);
}
void GP::construction_vecteur_A_B_(std::vector<std::string> list_names_a, std::vector<std::string> list_names_b)
{
for (int i = 0; i < list_names_a.size(); i++) {
vecteur_noms_A_.push_back(list_names_a[i]);
}
for (int i = 0; i < list_names_b.size(); i++) {
vecteur_noms_B_.push_back(list_names_b[i]);
}
}
int main()
{
std::vector<std::string> list_names_A = std::vector<std::string>();
std::vector<std::string> list_names_B = std::vector<std::string>();
list_names_A.push_back("A");
list_names_B.push_back("B");
GP(list_names_A, list_names_B);
return 0;
}
Since the program written here weems to throw no error, I would like to uderstand why :
vecteur_noms_A_
and
vecteur_noms_B_
are existing at execution so that I can do the pushback. Why isn't it necessary to apply this to them in the constructor:
vecteur_noms_A_ = std::vector<std::string>();
vecteur_noms_B_ = std::vector<std::string>();
Thanks for your help.