Pastx
Pastx

Reputation: 767

Unknown return type error (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.

Upvotes: 5

Views: 363

Answers (5)

4pie0
4pie0

Reputation: 29724

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.

Upvotes: 3

Qaz
Qaz

Reputation: 61910

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.

Upvotes: 5

Dinesh Reddy
Dinesh Reddy

Reputation: 825

class Test {
class Inner {
};     
public:    
    Inner* foo (void);
};

Test::Inner* Test::foo(){
}

Upvotes: 2

László Papp
László Papp

Reputation: 53155

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.

Upvotes: 3

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

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.

Upvotes: 6

Related Questions