I don't understand as to why the code below gives a segmentation fault upon use of a pointer object. The code works fine, if non-pointer object is used, but gives a segmentation fault if pointer object is used to update the private vector member 'name'. The only way I got the pointer to work is to create a getter function for the vector member 'name', and use it as argument for the read_names() function.
Could the CPP experts explain why this is happening..?
This is the cpp file.
#include "iostream"
#include "string"
#include "vector"
using namespace std;
#include "name_pairs.h"
int main()
{
// The 2 lines below here is what works.
// Name_pairs pair1;
// pair1.read_names();
//This part below gives segmentation fault.
Name_pairs* pair1;
pair1->read_names();
delete pair1;
return 0;
}
This is the header file.
class Name_pairs
{
public:
void read_names();
// prompts the user for an age for each name.
void print();
private:
vector<string> name;
vector<double> age;
};
void Name_pairs::read_names()
{
// string in;
for (string in; cin>>in;)
{
name.push_back(in); //segmentation fault occurs here!
}
}
Aucun commentaire:
Enregistrer un commentaire