Different behavior between temporary and declared object

Koos Vriezen koos@polder.ubc.kun.nl
Fri Jun 4 05:52:00 GMT 1999


Hi,

Suppose I have these classes:

class A {
public:
  virtual void say () { cout << "Hello A\n"; }
};

class B : public A {
public:
  void say () { cout << "Hello B\n"; }
};

class C {
public:
  C (A & a) { a.say (); }
};

and I construct a C with a B like:

  C (B());

I get the this warning:

In function `int main()':
warning: initialization of non-const reference `class A &'
from rvalue `B'
warning: in passing argument 1 of `C::C(A &)'

When I run it, it prints 'Hello B'
C created a follows: 

  B b;
  C (b);

generates an error:

In function `int main()':
conflicting types for `class C b'
previous declaration as `class B b'
no matching function for call to `C::C ()'
candidates are: C::C(const C &)
                C::C(A &)


I agree with the compiler that there is an error, but isn't the first case
also wrong?


Cheers,

Koos Vriezen




More information about the Gcc mailing list