开发者

Will overrides be called when class instance was send as if it was type with out overrides?

开发者 https://www.devze.com 2023-02-08 05:11 出处:网络
Having Class B that extends class A and overrides its functions can we be sure that when sending instance of (B*) as开发者_如何学编程 if it were type (A*) our overrides we created in class B will be c

Having Class B that extends class A and overrides its functions can we be sure that when sending instance of (B*) as开发者_如何学编程 if it were type (A*) our overrides we created in class B will be called?


As long as the method on A is defined as virtual this will be the case for both pointers and references. For example

class A {
  virtual void Method() {
    cout << "A::Method" << endl;
  }
};

class B {
  // "virtual" is optional on the derived method although some
  // developers add it for clarity
  virtual void Method() {
    cout << "B::Method" << endl;
  }
};

void Example1(A* param) {
  param->Method();
}

void Example2(A& param) {
  param.Method();
}

void main() {
  B b;
  Example1(&b);  // Prints B::Method
  Example2(b);   // Prints B::Method
}


Yes, if the functions are declared virtual - see http://www.parashift.com/c++-faq-lite/virtual-functions.html


Only if the function in A is declared virtual. When declared virtual, any overriden child functions are called even when cast as a parent class.

0

精彩评论

暂无评论...
验证码 换一张
取 消