Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 929
Andreas Ziegler Avatar asked May 20 '26 07:05

Andreas Ziegler


1 Answers

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.

like image 179
lubgr Avatar answered May 21 '26 22:05

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!