Using a private nested type as a parameter

I get this strange problem that I don't know why this is happening. The first and second of the following code snippets are compiled, and the third is not:

Collects:

class Foo { public: Foo() { Bar(); } private: class Bar {}; }; 

Collects:

 class Foo { class Bar {}; // Or only forward declare here and define later public: Foo(Bar) {} } 

Not compiling:

 class Foo { public: Foo(Bar) {} private: class Bar {}; }; 

What makes the third compile while the first can?

+7
c ++
source share
2 answers

Usually in C ++ you can only refer to announcements that were previously made in the translation block. However, in a class definition, the definition of member functions is allowed to refer to declarations made later in the class. Basically, the compiler restructures your definitions in the class so that they work as if they were written right after the class.

But this only applies to function definitions. Declaring this function (including parameter types) is not allowed. They can only link to ads that have already been made in file order.

So you can do this:

 class Test { public: void Func(int x) {Inner foo;} private: class Inner {}; }; 

But not this:

 class Test { public: void Func(Inner x) {} private: class Inner {}; }; 
+4
source share

The first example does not reveal anything about the private Bar outside, while the third does.

The third example says pretty much that there is some class Foo that has a constructor with a single argument of type Bar . But Bar unknown to the outside. Imagine a call to such a constructor.

 Foo f{Foo::Bar{}}; 

It seems like something like Foo::Bar not available.

+2
source share

All Articles