Where can a virtual function be defined?

I have a question about virtual functions in C ++, for example A

is this base class and class B

inherits A

and class C

inherits B

, is it possible to define a virtual function in B

and override it in C

? I mean, should this virtual function be defined in the class A

because A

- is it the base class (i.e. Root B

and C

) for all B

and C

?

+3


source to share


3 answers


There is no need to be ... B is a specialized object from A, and most likely B has more capabilities than A. And if C is inferred, it is very normal to have a function overridden from B that is not defined in A.

Example



  • Suppose A is the shape
  • Suppose B is a circle ... the circle has a GetDiameter function that has no shape.
  • Assuming C is an ellipse, although the ellipse has no real diameter, the GetDiameter function is redefined to get the diameter of the "smallest" of the two diameters.
+4


source


virtual

can be used anywhere in the class hierarchy, but this virtual function can only be overridden in subclasses (i.e. it does not apply to superclasses).



struct A {
  void funcA();
};

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

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

//....
  B* b = new C();
  b->funcB(); // calls C implementation
  A* a = new C();
  a->funcB(); // fails to compile

      

+3


source


Yes, this is not a problem at all - try:

class A
{

}

class B : public A
{
public: 
 virtual void myFunc(): { std::cout << "B here!"; }
}

class C : public B
{
public: 
 virtual void myFunc(): { std::cout << "No, C here!"; }
}

      

+1


source







All Articles