简体   繁体   中英

Cannot initialize pointer to a subclass with base clase rvalue

I have a question regarding a problem in a C++ exam. I had quite an argument with a teaching assistant and I want to know, if I missed something.

Given is the following code:

class Student {
public:
  virtual void checkFinanes() {
    std::cout << "I have no money. \n";
  }
};

class ExonomyStudent : public Student {
public:
  virtual void checkFinances() {
    std::cout << "I am making a lot of money.\n";
  }
};

The question is:

Does the following code compile? If so, what is the output on the console when i is expected. If not, why not?

Student student;
student.checkFinances();
EconomyStudent* economyStudent = &student;
economyStudent->checkFinances();

And the answer is supposed to be:

Does not compile. Cannot initialize EconomyStudent * with Student rvalue.

I am aware and understand, that one cannot initialize a pointer to a subclass with and address of an object of a baseclase and that this does not compile. What I don't understand is the rvalue. Is it really important that rvalue is stated to make the answer valid? My teaching assistant insisted but I don't think so. What do you think?

Is it really important that rvalue is stated to make the answer valid?

I don't think so. Check the case where you try to initialize EconomyStudent *economyStudent with an lvalue:

 Student student;
 student.checkFinances();
 Student *lvalue = &student;
 EconomyStudent* economyStudent = lvalue;

clang complains on my machine, stating that

error: cannot initialize a variable of type 'EconomyStudent *' with an lvalue of type 'Student *'

Hence, the only difference in terms of compiler output is rvalue vs. lvalue. As the value category has nothing to do with the type of error in the snippet, you can tell your teaching assistant that some random user on the internet thinks that you are right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM