My problem is that i need to first define my interface and then implement it further in code but my problem i that function that should return type that is known inside class seems to be unknown outside class when i implement method.
This is my code:
class Test {
class Inner {
};
public:
Inner* foo (void);
};
Inner* Test::foo(){
}
This code produce error because type Inner is unknown for the function outside the class. Can anyone help me how to make simple function that would return type defined only inside class ?
Thank you for any help.
You need
Test::Inner* Test::foo(){
}
If a member function definition is outside the class definition, then the return type is not in the class scope, unlike the rest of the function, so you need to explicitly qualify the return type.
Since no one has mentioned it, you can also do this in C++11:
auto Test::foo() -> Inner * {...}
This can be useful if the fully qualified name is long. In C++14, you can leave off the trailing type part and just do:
auto Test::foo() {...}
This will deduce the return type.
Inner is a nested class and outside class Test
it has to be fully qualified:
Test::Inner* Test::foo() {
//...
}
because in global scopeInner
is indeed unknown, only Test::Inner
, so a Inner
inside Test
is known. You could also have another Inner
in global scope, just the same as with Test
, and this will be other Inner
, not Test::Inner
.
You does not seem to specify the scope so it, of course, remains unknown. The C++ compiler will look for an Inner
class outside your Test
class which could also present as a different class, but it is not in your particular case.
That is why you will need to also provide the scope, even for the return type. That is not to say you would need to use the scope inside your test class, but outside, you will have to due to that.
Thereby, the correct code would be something like this:
class Test {
class Inner {
};
public:
Inner* foo (void);
};
Test::Inner* Test::foo(){
//^^^^
}
Strictly speaking, if you have a recent compiler, you could even use auto, but then it gets a bit less comprehensive.
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