Nitin Kashyap
Nitin Kashyap

Reputation: 184

Error while compiling in gcc

I am doing a project for my class where the instructor had given us some code snippets and we were asked to modify it. The code compiles correctly in my class computer in Visual Studio but when I try to compile it with gcc it gives me an error. The error I am getting is:

||=== Build: Debug in Project (compiler: GNU GCC Compiler) ===|
/home/nitin/Read.h|45|error: declaration of ‘std::vector<rv> rvs::rv’ [-fpermissive]|
/home/nitin/Read.h|35|error: changes meaning of ‘rv’ from ‘struct rv’ [-fpermissive]|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

The code from the error is snippet for this is:

struct rv
{
    double val, prob;
    rv(const double v, const double p): val(v), prob(p) {};
};


struct rvs
{
    int row_n, col_n;
    vector<rv> rv;
    rvs(const int r=-2, const int c=-2): row_n(r), col_n(c) {};
};

Could you please let me know what the problem could be?

Upvotes: 0

Views: 357

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320491

Your declarations violate the following rule

3.3.7 Class scope [basic.scope.class]

1 The following rules describe the scope of names declared in classes.

...

2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

At the point of vector declaration name rv refers to a type struct rv. But when reevaluated in the scope of complete class rvs it, refers to class member rvs::rv. Such inconsistency is an error in C++.

A similar error is illustrated by an example in the standard

enum { i = 1 };

class X {
  char v[i]; // error: i refers to ::i
             // but when reevaluated is X::i
  ...
  enum { i = 2 };
};

As @Ben Voigt stated in the comment, if you explicitly resolve the conflict between rv as struct rv and rv as rvs::rv, the error will go away. You can do it by either using elaborate type specifier struct rv or by specifying scope explicitly ::rv.

Note that this is one of those errors which are not guaranteed/required to be caught by the compiler.

Upvotes: 3

Alan Stokes
Alan Stokes

Reputation: 18964

You have a type called rv and a member variable called rv. How is the compiler supposed to know which one you mean when you write rv?

Strictly this is invalid code, but Visual Studio seems to be willing to try to let you shoot yourself in the foot.

Upvotes: 0

Related Questions