borna morasai
borna morasai

Reputation: 45

How can I access the class variables inside the print() function here?

Book.h

class Book{
private:
    std::string title;
    std::string author;
    int callNo;
public:
    Book(std::string title,std::string author,int callNo);
    void print();

};

Book.cpp

Book::Book(string title,string author,int callNo){
    this->title=title;
    this->author=author;
    this->callNo=callNo;
}

void print(){
    cout<<"Title: "<<title<<endl;
    cout<<"Author: "<<author<<endl;
    cout<<"Call Number: "<<callNo<<endl;
}

When compiling, I get the error:

Book.cpp:14:19: error: ‘title’ was not declared in this scope cout<<"Title: "<<title<<endl;

Is there anyway of calling the class variables without changing the parameters of print()?

Upvotes: 1

Views: 49

Answers (1)

nvoigt
nvoigt

Reputation: 77285

Since it's a member function of Book, it should be

void Book::print(){
     std::cout << "Title: " << title << std::endl;
     std::cout << "Author: " << author << std::endl;
     std::cout << "Call Number: " << callNo << std::endl;
}

Upvotes: 1

Related Questions