Results 1 to 2 of 2

Thread: question regarding virtual methods

  1. #1

    Thread Starter
    Member
    Join Date
    Oct 2000
    Posts
    34

    question regarding virtual methods

    I understand what a virtual function is:

    Code:
    class Base
    {
    public:
      virtual int DoSomething();
      int DoSomethingElse();
    };
    
    class Derived : public Base
    {
    public:
      int DoSomething();
      int DoSomethingElse();
    };
    
    int main(void)
    {
      Derived* d = new Derived;
      Base* b = d;
    
      d->DoSomething();  // Calls Derived::DoSomething()
      b->DoSomething();  // Calls Derived::DoSomething()
    
      d->DoSomethingElse();  // Calls Derived::DoSomethingElse()
      b->DoSomethingElse();  // Calls Base::DoSomethingElse()
      d->Base::DoSomethingElse();  // Calls Base::DoSomethingElse()
    
      delete d;
    
      return 0;
    }
    My question is: Why wouldn't you make all functions virtual?
    I am just learning C++ and this concept doesn't make alot of sense right now. Also, does a virtual function have to be overriden by a derived class???

    Thanks for any help

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Sometimes you want to call the function related to that pointer's type, or you may want to specifically call a base class function on a derived class. That's why there's a choice.

    Virtual functions don't have to be overridden unless they're Pure Virtual Functions, the presence of which create an abstract class that can't be used, only derived from:
    Code:
    class Base {
    public:
        int MyFunction(int x) = 0; // Pure virtual
    };
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width