1

I came across the following code and I couldn't find on google why the following statement is valid C++ :

Base&& b = Derived();

Please explain or give reference

Here is a sample code :

#include <iostream>
using namespace std;

class Base{
public:
    virtual ~Base(){}
    virtual void say_hi() { cout << "hi base"; }
};
class Derived : public Base{
public:
    virtual ~Derived(){}
    virtual void say_hi() { cout << "hi derived"; }
};

int main(int argc, const char * argv[]) {
    Base&& b = Derived();
    b.say_hi();

    return 0;
}

prints :

hi derived
jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
Julien__
  • 1,962
  • 1
  • 15
  • 25

1 Answers1

8

This is binding a temporary to an r-value reference. Temporaries may be bound to both constant l-value references and r-value references.

As for why it's properly calling the derived function, that's because you're calling a virtual function. Dynamic dispatch is taking place as normal.

This is sort of the same as using a function call with an r-value reference parameter:

void callHi(Base&& b){
  b.say_hi();
}

...

callHi(Derived{}); // ultimately calls derived say_hi method

You mention slicing. For slicing to occur, the sequence of events is a bit more complex than simply calling a virtual function.

Community
  • 1
  • 1
jaggedSpire
  • 4,423
  • 2
  • 26
  • 52