2

In this complete code:

class foo
{
  public:
    foo(const int pin);
};

class bar {
  public:
    // Constructor
    bar(const int dataPin) : dataPin_ (dataPin) { }

  private:
    const int dataPin_;
    foo myFoo_ (dataPin_);  // instance of foo
};

int main (void)
  {
  return 0;
  }

Using g++ 4.8.4 I get the error:

g++ -Wall -c "test.cpp" (in directory: /home/nick/Development)
test.cpp:14:17: error: ‘dataPin_’ is not a type
     foo myFoo_ (dataPin_);  // instance of foo
                 ^
Compilation failed.

Using clang 3.4-1ubuntu3 I get:

test.cpp:14:17: error: unknown type name 'dataPin_'
    foo myFoo_ (dataPin_);  // instance of foo
                ^
1 error generated.

Why does it want a type here? This is attempting to create an instance of foo as a class variable of bar. The variable dataPin_ is declared directly above.


If I change the line with the error to this, it compiles cleanly:

    foo myFoo_ (int dataPin_);  // instance of foo
Nick Gammon
  • 1,173
  • 10
  • 22
  • 2
    You have to initialise `myFoo_` in the `bar()` constructor like any other member of the class. – Jonathan Potter Jun 26 '16 at 23:31
  • Even if you turn on C++11, using parens for in-class data member initialization still isn't allowed (as opposed to braces or =). – chris Jun 26 '16 at 23:34
  • 2
    foo myFoo_ (dataPin_); // instance of foo. Is that supposed to be a function or variable? – Alex Zywicki Jun 26 '16 at 23:35
  • That line is supposed to be a variable - an instance of `foo`. – Nick Gammon Jun 26 '16 at 23:50
  • I don't think it is a duplicate personally. I didn't ask about in-class initializers, and the "duplicate" question certainly did not appear when I searched for that error message. – Nick Gammon Jun 27 '16 at 21:56

2 Answers2

8

It's reading foo myFoo_ (dataPin_); as a function declaration: myFoo_ is a function taking a dataPin_ and returning a foo. That's why it's expecting a type name in ( ).

To fix this, initialize myFoo_ in your constructor, just like you did with dataPin_:

bar(const int dataPin) : dataPin_ (dataPin), myFoo_(dataPin) {}
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • OK, I see it now. The "fix" I used merely turned the line into a function prototype. What you suggested compiled OK - along with changing the line in error to merely: `foo myFoo_; ` – Nick Gammon Jun 26 '16 at 23:52
-1

Here you should add type not variable, this is the function signature, it should has types not variables.

foo myFoo_ (dataPin_);  // instance of foo
MoustafaS
  • 1,991
  • 11
  • 20
  • 1
    "Here you should add type not variable" doesn't answer the question "Why does it want a type here?", it just repeats what the compiler said. – melpomene Jun 26 '16 at 23:40
  • I was editing it to explain more, and then I saw your answer, so I left it as I was going to say the same as you :) . @melpomene – MoustafaS Jun 26 '16 at 23:41