Guilherme Gil
Guilherme Gil

Reputation: 51

Returning structures in functions results in incompatible declaration

So, i have two files interpretor.h and interpretor.cpp. I want to have a method to return a struct but it is always saying that i cannot convert to to incomplete class or declaration is incompatible. Could someone help me? I will put some code here:

interpretor.h

#pragma once

#include <iostream>
#include "calc3.h"

class interpretor
{
public:
    interpretor(nodeType* STprogram);

private:
    /* for passing informations */
    struct returner {
        union
        {
            int integer;
            float real;
        };

        int type;
    };
    
    struct returner test();
};

and interpretor.cpp

#include "interpretor.h"

// ...

struct returner interpretor::test() {
    returner p;
    return p;
}

Upvotes: 1

Views: 66

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41770

The error come from struct returner declaring a new forward declared type when it is not found. In your case, the type is not found so it create a new one, hence you incompatible declaration error. If you dropped the struct in front of the returner, it would show a more helpful error:

<source>:7:1: error: 'returner' does not name a type
    7 | returner interpretor::test() {}
      | ^~~

When using a member type of a class, you must use the qualified name of the type:

interpretor::returner interpretor::test() {
    returner p;
    return p;
}

Alternatively, you can use trailing return types which makes it easier for the compiler to find the names:

auto interpretor::test() -> returner {
    returner p;
    return p;
}

Upvotes: 4

MikeCAT
MikeCAT

Reputation: 75062

The structure returner is declared inside the class interpretor, so the name of the class should be added outside class { } and { } in member function definitions.

struct interpretor::returner interpretor::test() {
    returner p;
    return p;
}

Upvotes: 1

Related Questions