Classes Help

I created this program but when I output it it outputs random numbers

#include <iostream>

using namespace std;

class Book {
private:
int booknum;
string bookname;
public:
void setbookNum(int x) {
x = booknum;
}
int getbookNum() {
return booknum;
}

void setbookName(string b) {
b = bookname;
}

string getbookName() {
return bookname;
}
};



int main()
{
Book book1;
book1.setbookNum(1);
book1.setbookName("Sherlock Holmes");

cout << book1.getbookNum() << " " << book1.getbookName() << endl;
}
When you are assigning variables it is the value on the LHS of the = which is set. Thus, in setbookNum() you need
booknum=x
and in setbookName() you need
bookname=b

The application doesn't seem to be one for which having a lot of setters and getters is sensible. After all, we don't usually change the titles of books. Consider setting these member variables in a constructor.


Please use code tags.
Last edited on
Topic archived. No new replies allowed.