Linksx
Linksx

Reputation: 260

C++ error using references

I'm working at a project, and it is the first time when I work with pointers and references, and at this moment I need to set a reference to the Author who wrote a book, as a parameter in constructor. I also want to return a constant reference to the author, using getAuthor() method. I can't understand why I have that error (commented lines).

Book.h

class Book{
private:
    std::string bookTitle;
    const Author &bookAuthor;
    std::string bookLanguage;

public:
    Book(std::string _title, const Author &_author, std::string _language);
    Book();
    ~Book();
    Author getAuthor();
};

Book.cpp

#include "Book.h"

Book::Book(std::string _title, const Author &_author, std::string _language) 
: bookTitle(_title), bookAuthor(_author), bookLanguage(_language){
}

Book::Book(){ // error C2758: 'Book::bookAuthor' : a member of reference 
              // type must be initialized
}

Book::~Book(){
};

Author Book::getAuthor(){
    return bookAuthor;
}

Upvotes: 0

Views: 66

Answers (1)

iBug
iBug

Reputation: 37287

A reference is essentially an alias for an existing object. It must be initialized upon definition. You can't say "<a name>" is an alias for whatever you don't know.

A reference must be initialized and cannot be changed after initialization.

In your case, if you want to have a default constructor that does not assign anything, you'd better create an object representing "unassigned" and use that.

private:
    static const Author nullAuthor(a_flag_that_means_unassigned);
public:
    Book::Book() : bookAuthor(nullAuthor);

If you want to assign ot change it later, use a regular object. Make sure you have a copy assigner for class Author.

private:
    Author bookAuthor;
public:
    Book::Book(); // Now it's safe to leave it uninitialized

Upvotes: 1

Related Questions