2

I have some problems understanding why gcc gives me an error, when I try to pass a derived object to a function, that takes a base class reference.

class Base 
{
public:
    virtual void bar(){}
};

class Derived : public Base
{
public:    
    virtual void bar() {}
};

void foo(Base& base)
{
    base.bar();
}

int main()
{

    Derived derived();
    foo(derived);

    return 0;
}

gcc returns following which i can't understand:

In function 'int main()':
29:16: error: invalid initialization of reference of type 'Base&' from expression of type 'Derived()'
     foo(derived);
                ^
19:6: note: in passing argument 1 of 'void foo(Base&)'
 void foo(Base& base)
      ^~~
mch
  • 9,424
  • 2
  • 28
  • 42
Paul Groskopf
  • 31
  • 1
  • 3

0 Answers0