View Single Post
Old May 11th, 2006, 5:36 AM   #3
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Wet west coast of Canada
Posts: 1,107
Rep Power: 5 lectricpharaoh will become famous soon enough
Quote:
Originally Posted by ASH
could sum1 plz explain the comparison between ordinary member functions & polymorphic member functions.
Ordinary methods (member functions) are all resolved at compile (or link) time, while virtual (polymorphic) methods are usually resolved at run time.

Here is an example to make things a little clearer, hopefully:
#include <iostream>

class fruit
{
  public:
  virtual void printName(void);
};

void fruit::printName(void)
{
  std::cout << "I am a generic fruit.\n";
}

class apple:public fruit
{
  public:
  void printName(void);
};

void apple::printName(void)
{
  std::cout << "I am an apple.\n";
}

int main(int argc, char *argv[]);
void printFruitName(fruit &f);

int main(int argc, char *argv[])
{
  fruit foo;
  apple bar;
  printFruitName(foo);
  printFruitName(bar);
  return 0;
}

void printFruitName(fruit &f)
{
  f.printName();
}
If you run this program, you should see the following output:
I am a generic fruit.
I am an apple.
Notice how the output is different, even though both times, the call is made through the f.printName() method. Now, since the body of the printFruitName() function is fixed, there must be some mechanism that determines which method to call based on the run-time type of the object. This is referred to as polymorphism, and it is a key property of object-oriented programming languages.

The way in which it is implemented can vary from one language to another, but in C++, it is generally (always?) done with a 'vtable', which is a table of pointers to the virtual (hence the 'v') methods. When objects are constructed, the table entry (or entries) are filled in with a pointer to the actual method. This makes the code slightly longer and slower, which is why virtual methods are not the default (there is no reason to accept a performance hit unless it is required). However, virtual methods offer lots of flexibility in your programming, and allow you to write less code (or reuse more existing code) than would otherwise be possible, and when you need to determine the method to call at run-time, doing it through a technique like a vtable is the most efficient means. The other option is some immense switch() statement (or similar construct) that examines a 'type' data member set by the constructor, and this is obviously a bad idea.

[edit] Oh yeah, like nnxion said, English is a good idea. Butchering the language for 'leet-speak' just makes you look silly, stupid, or annoying. [/edit]
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote