Fandom

C Plus Plus

Virtual functions

16pages on
this wiki
Add New Page
Talk0 Share

Virtual Functions Edit

Virtual Functions are methods that can be overridden in a subclass. That means you can provide a specialized implementation of the method in a subclass, and that implementation will be used. Consider this example:

class A
{
  public:
  virtual int virtual_func()
  {
    //Do something
  }
}

class B : public class A
{
  public:
  virtual int virtual_func()
  {
    //Do something different
  }
}

In code somewhere else:

A* foo = new A;      // make "foo" point to a new A object
foo->virtual_func(); // this calls A's "virtual_func"
A* bar = new B;      // make "bar" point to a new B object; "bar" is declared as an A pointer
                     // B is a subclass of A; so we can use it as an A
bar->virtual_func(); // this calls B's "virtual_func", even though "bar" is of type "pointer to A"
                     // this works because B has overridden A's virtual function of the same name

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.