Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can a virtual function be defined?

I have a question about virtual functions in C++, for example, A is a base class, and class B inherits A, and class C inherits B, can we define a virtual function in B, and redefine it in C? What I mean is, should this virtual function be defined in class A, because A is the base class (i.e the root of B and C) for all the B and C?

like image 561
ratzip Avatar asked Jun 02 '26 23:06

ratzip


2 Answers

Not it does not have to be ... B is a specialized object from A and it is high likely B has more features than A has. And if C is derived, it is very normal to have a function overridden from B which is not defined in A.

Example

  • Let's assume A is a Form
  • Let's assume B is a Circle ... a circle has a GetDiameter function, which a form does not have.
  • Let's assume C is an Ellipse, although an ellipse has not a real diameter, the GetDiameter function is overridden to get the diameter of the 'smallest' of the two diameters.
like image 88
Michel Keijzers Avatar answered Jun 05 '26 02:06

Michel Keijzers


virtual can be used anywhere in a class hierarchy, but that virtual function can only be overridden in the sub-classes (i.e. it does not apply to the super classes).

struct A {
  void funcA();
};

struct B : A {
  virtual funcB();
};

struct C : B {
  virtual funcB();
};

//....
  B* b = new C();
  b->funcB(); // calls C's implementation
  A* a = new C();
  a->funcB(); // fails to compile
like image 35
Niall Avatar answered Jun 05 '26 00:06

Niall



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!