If you declare a function to be virtual in a base class and then you derive another class from the base class and call the function, you will get the derived function instead of the base class function. So suppose you have:
class CShape {
...
virtual int dostuff() { return 0; }
}
class CCircle : public CShape {
...
int dostuff() { return 1; }
}
and then in your main program you do this:
CShape foobar = new CCircle();
int i = foobar.dostuff();
You will get back 1 from the dostuff() call, even though the type of the object you are using in CShape. That is because CShape will see that the dostuff function is virtual and that really your object is a CCircle, and it will call CCircle::dostuff(). If you had not made the function virtual, you would have gotten a return of 0 (CShape::dostuff())
Hope that helps.
2006-09-26 08:47:28
·
answer #1
·
answered by Larry 6
·
1⤊
0⤋
"A virtual function is so named because it may, in a sense to be made clear, be used before it is defined. Virtual functions will prove to be another tool for software reuse."
By the way, in C++ you can overwrite any base class function in derived class: it must not be virtual at all.
2006-09-26 10:33:17
·
answer #2
·
answered by alakit013 5
·
0⤊
0⤋
If you declare a function or method as virtual in a class, the same can be overridden in derived classes
2006-09-26 09:49:54
·
answer #3
·
answered by yesu v 1
·
0⤊
0⤋
It's a called some time friend function. This is a empty function.
2006-09-26 18:25:44
·
answer #4
·
answered by togopi_27 1
·
0⤊
0⤋
means a subclass or derived class can override a method/function that is in the parent/superclass/base class
2006-09-26 08:44:52
·
answer #5
·
answered by Nick F 6
·
0⤊
0⤋