Forward references in class definition
-
I always thought/assumed you could not do this:
class Foo { public: int getter() const { return _thing; } private: int _thing; };
I do mean in specifically that order. I thought when it met the early
return _thing;
compiler would complain "_thing
not defined".I now discover you can do that, which surprised me. So this means compiler is doing two passes over this (e.g. in
.h
file), first just for declarations and then second for code generation.Now that I think about it, of course this applies too if the first method were calling another method defined later in the class, and that would not surprise me, else you'd have to be careful about the order of declarations in class/
.h
file. I guess I just had a mental block on variables.Don't know what anyone else would care to comment on this as I guess there is not much of a question here! I sort of thought code was generated as it did single pass though class declaration if that had code blocks in it, but clearly not?
-
Hi,
My memory is a bit rusty about that topic but IIRC, in the class/struct case, the compiler "waits" to have the whole declaration before it starts name resolution.
-
@JonB
Now you may know why this worksclass Foo { public: Foo() : _thing{5} {}/* setting here */ int getter() const { return _thing; } private: const int _thing; };
this does not work
class Foo { public: Foo() { _thing = 6;} /* _thing can not be changed anymore */ int getter() const { return _thing; } private: const int _thing; };
all member variables are declared first before the constructor func is called. The order of variables do matter if the first one uses the second one.
-
As @Christian-Ehrlicher might say : Basic C++ stuff
:) -
-
@JonB said in Forward references in class definition:
I always thought/assumed you could not do this:
Bjarne Stroustrup had some discussions with colleges. His first intuition was to actually not allow this. However, in the end the following idea won: It should not matter if you are defining a member function inside a class or outside of it. The visibility of member variables for member functions written inside the class should be the same as if defined outside. This allows to freely move member functions inside the class or outside. We are quite lucky that this was the final decision!
-
@SimonSchroeder said in Forward references in class definition:
Bjarne Stroustrup
This guy had time to design C++ at the same time as doing Abba? Amazing.
-
@JonB said in Forward references in class definition:
Abba
That one is Björn Ulvaeus (he is Swedish, whereas Bjarne is Danish).
-
@SimonSchroeder
Details! And as far as I know Denmark & Sweden are more or less the same country anyway ;-)