Bob John
Bob John

Reputation: 3888

In what order are methods called when you have 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 wanted 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;
}

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

Thank you.

Upvotes: 4

Views: 114

Answers (1)

Joshua D. Boyd
Joshua D. Boyd

Reputation: 4866

Once you sorted out the error in Laptop *s = d; (see static_cast<>()), you would find that HPdv6's remaining_time() would be called and Laptop's power_save() would be called.

To over-simplify, the functions are resolved by starting at HPdv6 and walking up the inheritance tree until the method is found. IPad won't be used because it doesn't appear between HPdv6 and Laptop, it sits in a separate branch.

If you want the non-oversimplified version, look up vtables. Here is the Wikipedia article on them: http://en.wikipedia.org/wiki/Virtual_method_table

Upvotes: 3

Related Questions