Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why defining a method with a return type as its class won't get me an 'incomplete type' error

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.)

like image 355
longtengaa Avatar asked Nov 25 '25 16:11

longtengaa


1 Answers

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.

like image 143
bstamour Avatar answered Nov 28 '25 05:11

bstamour