chrise chrise - 1 year ago 58
C++ Question

c++ why does this forward declaration fail?

I have a Class with the following .h

class Book; //forward declaration of Book

class Reader

void SetBook( Book );


Book book_; // Error Reader::book_ uses undefined class Book


and .cpp contains

#include "book.h"

void Reader::SetBook( Book book ) { this->book_ = book; }
// Error C2440 cannot convert from Book to int

I can't see why this forward declaration would does not work.
Also, it does not throw an error for the 'Book' type being used in the declaration

void SetBook (Book )

Any suggestions what's wrong, here?

Answer Source

A forward declaration is enough when you declare a pointer or a reference. Because your member book_ is of type Book the compiler needs the definition of Book when processing the header.