Dreaded Segmentation fault 11

This code compiles, but on run throws Segmentation fault 11:

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <string>

using namespace std;
        
class Cell {
   protected:
        string query;
	string val;
   public:
        void setVal();
        string getVal() {return val;}
        string getQuery() {return query;}
    virtual void flow(){cout << "*** Error: accessed Cell.flow() \n";};
   };
 
void Cell::setVal(){
      cout << getQuery() << " [y/n] ";
      cin >> val;
      if ((getVal()!="y") && (getVal()!="n")){
         while ((getVal()!="y")&&(getVal()!="n")){
            cout << "Please enter y or n: ";
            cin >> val;
         }
      }
}

class LinkCell: public Cell {
	Cell *yQuery;
	Cell *nQuery;
   public:
	LinkCell(string,Cell*,Cell*);
	void flow();
};

LinkCell::LinkCell (string setQuery, Cell *yLink, Cell *nLink) {
	query = setQuery;
	*yQuery = *yLink;
	*nQuery = *nLink;
}

void LinkCell::flow(){
	cout << "--> Reached setVal for LinkCell " << getQuery() << endl; setVal();
        if (getVal()=="y"){cout << "==> Reached getVal=y : atttemping to execute yQuery '" << yQuery->getQuery() << "'" << endl; yQuery->flow();}
        if (getVal()=="n"){cout << "==> Reached getVal=n : atttemping to execute nQuery '" << nQuery->getQuery() << "'" << endl; nQuery->flow();}
}

class EndCell: public Cell {
	string yEnd;
	string nEnd;
   public:
	EndCell(string,string,string);
    void flow();
};

EndCell::EndCell (string setQuery, string yMessage, string nMessage){
	query = setQuery;
	yEnd = yMessage;
	nEnd = nMessage;
}


void EndCell::flow(){
	setVal();
    if (getVal()=="y"){cout << yEnd << endl;}
    if (getVal()=="n"){cout << nEnd << endl;}
}

int main(){

	EndCell sorry("Do you want me to feel sorry for you?","I'm sorry for you","I'm not sorry for you");
	EndCell happy("Do you want me to feel happy for you?","I'm happy for you","I'm not happy for you");
	EndCell work("Do you want to work now?","Let's do it!","Let's hang out");
	LinkCell help("Can I help you?",&work,&sorry);
	LinkCell ok("Are you ok?",&happy,&help);

	ok.flow();

return 0;
}
In LinkCell::LinkCell function pointers are not initializes.
it should be like this.

1
2
3
4
5
6
7
LinkCell::LinkCell (string setQuery, Cell *yLink, Cell *nLink) {
        query = setQuery;
        yQuery = new(Cell);
        nQuery = new(Cell);
        *yQuery = *yLink;
        *nQuery = *nLink;
}
you are fast Rishi :D
i just wanted to paste the same code lol

don't foget to free up memory!
1
2
3
4
5
public:
      ~LinkCell() {
     delete yQuery;
     delete nQuery;
}
thank you codekiddy :D
Thanks! Solved.
Topic archived. No new replies allowed.