afduggirala wrote: |
---|
1. When you say "You can only use a reference .." . Why do you use the word "reference" here, you are not talking about an actual C++ reference, you are simply talking about using a user defined type (class) in the declaration of another class right?
|
The important word here is
use. Yes, it's talking about actual C++ references. You can store and pass a reference using just a forward declaration. But if you actually want to
use it, then the code that uses it will need to know the complete definition of the type.
This makes sense when you think about it - the compiler wouldn't be able to understand any code that tries to actually use a reference to something, without knowing the definition of its type, any more than it could understand code that uses any other kind of entity.
2. This situation makes me wonder, what is the best/common practice when declaring multiple classes that might depend on each other. Is it just best to have a header file and a corresponding cpp file for each individual class?
|
Generally, yes. It helps keep your compilation times down, and helps keep your header files easier for users to read if they're not cluttered with loads of implementation detail.
When is inline definition useful or appropriate? |
That's a bit of a can of worms, and different people will have different opinions. One place where it's definitely a good idea is in class templates. In order to generate code from a template, the compiler will need access to the full definition of the template, so it should all be in the header.
(There are tricks to get around this, but honestly it's just easier to put it all in there.)
If I use forward declaration like I have done, and try to use a copy (new memory?) of an object, I again get the compiler error saying "incomplete type" |
Yes. This falls under the category of "
using a reference", as discussed above. To create an object, the compiler needs to know the full definition of its type - otherwise how could it know what to create?
Its funny how "derefencing" 'this' actually gets me a reference. |
If, when you dereferenced a pointer, you got a copy of the object being pointed to, rather than simply a reference to it, it would be a lot less useful.
Yes, it's unfortunate that the terminology is a bit clumsy, in that the word "reference" can mean both a general concept, and a specific C++ syntactic construct. That's what happens when one language (C++) evolves from an older one (C).