Thread: Virtual/Overidden class methods

  1. #1
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Location
    Staffordshire University, UK
    Posts
    168

    Virtual/Overidden class methods

    I've recently been reading about virtual and over-riding class methods, and wondered what the difference really is, and whether it matters to use either.
    I know the virtual functions enable the function to do different things in different classes, but surely you can just over-ride the function and get the same effect?

    Dunno if it would be too much to ask for an example of where each would be appropriate, thanks!

  2. #2
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Code:
    #include <iostream>
    
    struct base
    {
       virtual void f() const { std::cout << "base::f()" << std::endl; }
       void g() const { std::cout << "base::g()" << std::endl; }
    };
    
    struct derived : public base
    {
       virtual void f() const { std::cout << "derived::f()" << std::endl; }
       void g() const { std::cout << "derived::g()" << std::endl; }
    };
    
    int main()
    {
       base foo;
       derived bar;
       
       foo.f();
       foo.g();
    
       bar.f();
       bar.g();
       
       base* ptr = &bar;
    
       ptr->f();
       ptr->g();
    }
    There most certainly is a difference.

    *edit*
    And here is a very relevant link: It's legal, but it ain't moral.

    Cheers
    Last edited by Zach L.; 08-21-2005 at 09:51 AM.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  3. #3
    Let's do some coding! Welshy's Avatar
    Join Date
    Mar 2005
    Location
    Staffordshire University, UK
    Posts
    168
    alright, thanks. Oh and cheers for the link, should minimise the need to post om here asking about inheritance again, hehe

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  2. calling OpenGL methods from outside the main class
    By Hector in forum Game Programming
    Replies: 2
    Last Post: 06-22-2006, 07:23 AM
  3. Mmk, I give up, lets try your way. (Resource Management)
    By Shamino in forum Game Programming
    Replies: 31
    Last Post: 01-18-2006, 09:54 AM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM