Lajos Nagy
Lajos Nagy

Reputation: 9475

Why C++ compiler (gcc) thinks function is `virtual' field?

I have a the following method definition in my class:

virtual Calc* Compile(
  Evaluator* evaluator, ResolvedFunCall* fun_call, string* error);

For some reason, GCC complains that:

error: 'Compile' declared as a 'virtual' field

Any ideas why it would believe Compile to be a field, instead of a method?

Upvotes: 12

Views: 9981

Answers (2)

Ken_sf
Ken_sf

Reputation: 119

This happened to me when I declared a virtual function with {} instead of ().

A sample to demonstrate the error:

test.h

class Test{
public:
Test(){}
~Test(){}
//next line is defective, use () instead of {}
virtual int myfunct{int i};//notice brackets here which causes the error
};

test.cpp

#include "test.h"//i omitted include guards for simplicity
int Test::myfunct(int x){
    x=5;
    return x;
}

main.cpp

#include "test.h"
int main(){
    Test test;
    return 0;
    }

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507403

I get that error when the first parameter doesn't make sense to it. Check that Evaluator is known as type:

struct A {
    virtual void* b(nonsense*, string*);
};

=> error: 'b' declared as a 'virtual' field

struct A {
    virtual void* b(string*, nonsense*);
};

=> error: 'nonsense' has not been declared

To find out whether something is a object or function declaration, the compiler sometimes has to scan the whole declaration. Any construct within the declaration that could possibly form a declaration is taken to be a declaration. If not, then any such construct is taken to be an expression. GCC apparently thinks because nonsense is no valid type, it can't be a valid parameter declaration, and thus falls back treating the whole declaration as a field (note that it says in addition error: expected ';' before '(' token ) . Same thing in local scope

int main() {
    int a;

    // "nonsense * a" not treated as declaration
    void f(nonsense*a);
}

=> error: variable or field 'f' declared void

int main() {
    // "nonsense * a" treated as parameter declaration
    typedef int nonsense;
    void f(nonsense*a);
}

=> (compiles successfully)

Upvotes: 33

Related Questions