In what order is the method called when you have a class hierarchy?

Consider:

class Mobile { double memory_util; public: virtual void power_save(double duration) = 0; }; class Laptop : public Mobile { bool is_unlocked; protected: bool is_charged; public: void power_save(double duration); virtual double remaining_time(); }; class NegativeNumber {}; class IPad : public Laptop { int generation; public: void power_save(double duration); bool isJailBroken(); }; class HPLaptop : public Laptop { int warranty_years; public: void extend_warranty(int years); }; class HPdv6 : public HPLaptop { bool repaired; public: double remaining_time(){ return HPLaptop::remaining_time(); } bool is_repaired { return repaired; } }; 

And you would like to do the following:

 int main () { Mobile* d = new HPdv6(); Laptop *s = d; d->power_save(100); cout << "remaining operation time: " << s->remaining_time() << endl; return 0; } 

What methods will actually be called here? I understand that Mobile is a virtual function, but I'm not sure how to deal with the class hierarchy when you have pointers like this. Are there any class hierarchy tips that can make it easier to understand the problems associated with the various inherited classes?

Thanks.

+4
source share
1 answer

After you sort the error in Laptop *s = d; (see static_cast<>() ), you will find that HPdv6 remaining_time() will be called and Laptop power_save() will be called.

To oversimplify, functions are allowed, starting with HPdv6 and raising the inheritance tree until a method is found. IPad will not be used because it does not appear between HPdv6 and Laptop , it is in a separate branch.

If you need a non-simplified version, find vtables . Here is a Wikipedia article about them: http://en.wikipedia.org/wiki/Virtual_method_table

+3
source

All Articles