0

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;
}
Linksx
  • 250
  • 5
  • 25
  • 2
    `bookAuthor` must be initialized because it is a reference, what is not clear with this error? – user7860670 Aug 04 '17 at 11:00
  • 2
    A reference *must* reference something. That means it needs to be initialized. You can not have an "unset" reference variable. – Some programmer dude Aug 04 '17 at 11:00
  • Oh, I initialised it now with an object of type Author, and it works, thanks !!! – Linksx Aug 04 '17 at 11:02
  • 1
    Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – patatahooligan Aug 04 '17 at 11:11
  • @Linksx And where does your object you're referencing in the default constructor come from? You don't happen to simply create one right in the constructor? That sounds like you're entering undefined behaviour land. – Sebastian Stern Aug 04 '17 at 11:37
  • you mean `const Author &bookAuthor;` ? if yes, then I created an object `Author a` as a private member, and then I did `const Author &bookAuthor = a` – Linksx Aug 04 '17 at 11:40

1 Answers1

1

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
iBug
  • 35,554
  • 7
  • 89
  • 134