Different behavior between temporary and declared object

Koos Vriezen koos@polder.ubc.kun.nl
Wed Jun 30 15:43:00 GMT 1999


An instance of C created as:

  B b;
  C c;
  c.CC(b);

where C is redefined as:

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

compiles without warning!

> 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