Help please segmentation fault?

So for the last 20 minutes I've been trying to make this work but can't figure it out pleas help, also what does segmentation fault mean?.

Also this is my first attempt at something like this I'm trying to get it to change Adam into [Founder]Adam .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
using namespace std;

string name;

class NameStorage
 {
     public:
     void setName(string x)
     {
          name = x;
     }

     string getName()
     {
         return name;
     }

     string setPrefix()
     {
        if  (name=="Adam")
         {
              name="[Founder]Adam";
         }
     }

     private:
     string name;
 };

int main()
{
      NameStorage NS;
      
     cout << "what is your name?" << endl;
     cin >> name;
     NS.setName(name);
     NS.setPrefix();
     cout << "Welcome " << NS.getName();
     
     
     return 0;
}
Last edited on
A segmentation fault means your program has been corrupting memory and you got lucky and the OS noticed it and put a stop to id before things got out of hand. If you were unlucky, the program might have just kept running! Imagine the horror!
Thank you, probably doesn't help that im using an iPad c++ compiler app too low my computers broke atm.
try to add a return value to your function on line 20.
does that fix it?
Well, the issue is line 5. The string "name" is global. When you reach line 37, you take input and put it into name. Line 38 has you pass that value to NS.setName, which sets... name equal to the value passed to it. Which is "name" itself. If you look at line 29, you also created a string called "name" inside of the class. So when you get to NS.setName, specifically line 12, which name does it mean? setPrefix comes with the same issue- you are using a variable that is declared both as a global and as a member of a class, without distinction.
@Ispil: the functions in the class do not see the global name variable as the class member shadows it.
Topic archived. No new replies allowed.