I am trying to construct an object, and then set one of the variables to a value.
Class header:
class Book {
public:
Book();
Book(string newSelection);
string getSelection();
string setSelection(string newSelection);
private:
string selection;
}
Class cpp
Book::Book() {}
Book::Book(string newSelection) {
selection = newSelection;
}
string Book::getSelection(){
return selection;
}
string Book::setSelection(string newSelection){
selection = newSelection;
}
Driver
Book* book1 = new Book();
book1->setSelection("The Book Title");
cout << "Book selected: " << book1->getSelection() << endl;
I’m getting a segmentation fault, and am not sure why. Can somebody point out where my problem may be?
Your
setSelection()function is declared as returning a string but no string is actually being returned. You should get a compile warning at least for this.From running this through in a debugger, I believe that what’s happening is that following the call to
setSelection()the destructor is called on the returned string. As this string does not really exist, this causes anabort()within the runtime.As a general rule, ‘setters’ tend not to return anything so would be written as follows:
…
also note that the string is passed in by const reference rather than by value which is more efficient. This won’t be the cause of your problem though.
Another suggestion would be to ensure that your ‘getter’ is declared const as it doesn’t change anything in the object:
…