views:

124

answers:

1
+3  Q: 

queue from the stl

I am trying to get the following code to compile using g++ 4.2.1 and am receiving the following errors

CODE:

#include <iostream>
#include <queue>

using namespace std;

int main (int argc, char * const argv[])
{    
    queue<int> myqueue();
    for(int i = 0; i < 10; i++)
        myqueue.push(i);

    cout << myqueue.size();

    return 0;
}

ERRORS:

main.cpp: In function ‘int main(int, char* const*)’:
main.cpp:10: error: request for member ‘push’ in ‘myqueue’, which is of non-class type ‘std::queue<int, std::deque<int, std::allocator<int> > > ()()’
main.cpp:12: error: request for member ‘size’ in ‘myqueue’, which is of non-class type ‘std::queue<int, std::deque<int, std::allocator<int> > > ()()’

Any ideas as to why? I tried in Eclipse, X-Code and through the terminal.

+10  A: 

C++ FAQ Lite § 10.2

Is there any difference between List x; and List x();?

A big difference!

Suppose that List is the name of some class. Then function f() declares a local List object called x:

void f()
{
  List x;     // Local object named x (of class List)
  ...
}

But function g() declares a function called x() that returns a List:

void g()
{
  List x();   // Function named x (that returns a List)
  ...
}

Replace queue<int> myqueue(); by queue<int> myqueue; and you'll be fine.

ephemient
If further research is required, this is also sometimes known as the "most vexing parse": http://www.google.com/search?q=most+vexing+parse
Steve Jessop
that did it! thanks a lot. Out of curiosity, is there no constructor for the queue? I had the parentheses because I had to be calling the constructor. Or would I only do that if I were new-ing the object?
segfault
The version without parentheses does call the no-arg constructor.
Steve Jessop
`Foo bar;` constructs `bar` using the constructor `Foo::Foo()`. `Foo bar(a,b,c);` constructs `bar` using the constructor `Foo::Foo(a,b,c)`. `new Foo;` and `new Foo()` both construct a `Foo`, but mean subtly different things. Yes, this is inconsistent and horrible. That's C++ :) This is why some people prefer to write `Foo bar = Foo();` and `Foo bar = Foo(a,b,c);` but I don't really like that either...
ephemient
so Foo bar(); does NOT call the constructor Foo::Foo()? It must not if it produces a compile error.
segfault
No, `Foo bar()` does not construct anything. Instead, it is a declaration "in this scope, `bar` is a function taking no arguments and returning `Foo`". Of course, with only a declaration and no definition, you can't do anything useful with `bar`...
ephemient
ah. got it. thanks
segfault