This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Simple question: Can't I cast to a base class?


Rodrigo de Salvo Braz wrote:
> 
> When I compile
> 
> #include <iostream>
> #include <strstream>
> 
> void foo (istream& i) {}
> 
> int main (char* argv[], int argc)
> {
>         foo(istrstream("Simple."));
>         return 0;
> }
> 
> I get:
> t.cpp: In function `int main(char **, int)':
> t.cpp:8: initialization of non-const reference type `class istream &'
> t.cpp:8: from rvalue of type `istrstream'
> t.cpp:4: in passing argument 1 of `foo(istream &)'
> 
> Shouldn't that work since istrstream is a derived class of istream?
> Could anyone please explain that to me?

I suspect that this is off-topic, but it won't take long to answer.

A temporary variable (such as the temporary istrstream object in
your code above) is an "rvalue" because the Standard says so.  The
Standard goes on to say that you cannot bind an rvalue to a
non-const reference.  gcc helpful tells you this :)

If you changed foo to void foo (const istream &) { } then your
problem might go away.  Alternatively declare a named variable
for your istrstream and pass that to foo instead.

Hope this helps (and apologies for cluttering the gcc.gnu.org
mailing list).

I wonder if this is covered in any gcc FAQ...

-- James Dennett <jdennett@acm.org>

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]