Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown return type error (C++)

Tags:

c++

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.

like image 749
Pastx Avatar asked Apr 05 '14 16:04

Pastx


4 Answers

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.

like image 89
Armen Tsirunyan Avatar answered Sep 21 '22 13:09

Armen Tsirunyan


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.

like image 43
chris Avatar answered Sep 21 '22 13:09

chris


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.

like image 36
4pie0 Avatar answered Sep 23 '22 13:09

4pie0


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.

like image 43
lpapp Avatar answered Sep 23 '22 13:09

lpapp