As far as I know when defining a function with an object return type, while the class is only in its forward declaration state like this:
class A;
// forward declaration, which set A as an incomplete type
A foo(){...}
//error: A is an incomplete type I know it works fine when it has a return type of a pointer or reference to that object.
But when I define a method with a return type as its class:
class B{
public:
B foo(){...}
}
It works perfectly fine.
I think when defining a method within the definition of class, the class is still an incomplete type. So I think it will prompt error similar to the former, but it didn't. Does anyone know why?
I have searched for quite some time before asking for help here. (I'm not good at English, so my description may get you confused. Sorry for that.)
When defining methods inside a class the class is treated as if it were a complete type, or else we would not be able to define inline methods. Also, if your class A were an incomplete type then the curiously recurring template pattern would not work either. Consider the following code:
template <typename T> struct base {};
struct derived : base<derived> {}; // We can use derived here
// without any "incomplete type"
// errors.
In other words: it's just the way the language works.
EDIT: See Mike Seymour's below for the relevant section of the C++ standard that mentions this behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With