Wikia

C Plus Plus

Watchlist Recent changes

Virtual functions

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

Pages on C Plus Plus

Add a Page
15pages on
this wiki
Advertisement | Your ad here

Latest Photos

Add a Photo
3photos on this wiki
See more >

Recent Wiki Activity

See more >

Around Wikia's network

Random Wiki