Results 1 to 4 of 4

Thread: C++ virtual functions

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    May 2012
    Location
    Bangalore, India
    Posts
    271
    Thanks
    29
    Thanked 50 Times in 47 Posts
    Qt products
    Qt4 Qt/Embedded
    Platforms
    Unix/X11 Windows

    Exclamation C++ virtual functions

    Sir,
    I have a query about this vitual function. Look at this example:-
    Qt Code:
    1. using namespace std;
    2.  
    3. #include <iostream>
    4. class Animal {
    5. public:
    6. void eat() { //I have removed the virtual keyword here.
    7. cout << "I eat like a generic animal.\n";
    8. }
    9. // polymorphic deletes require a virtual base destructor
    10. //virtual ~Animal() {
    11. //}
    12. };
    13. class Wolf : public Animal {
    14. public:
    15. void eat() {
    16. cout << "I eat like a wolf!\n";
    17. }
    18. };
    19. class Fish : public Animal {
    20. public:
    21. void eat() {
    22. cout << "I eat like a fish!\n";
    23. }
    24. };
    25. class GoldFish : public Fish {
    26. public:
    27. void eat() {
    28. cout << "I eat like a goldfish!\n";
    29. }
    30. };
    31. int main() {
    32. Animal animal;
    33. Wolf wolf;
    34. Fish fish;
    35. GoldFish goldfish;
    36. animal.eat();
    37. wolf.eat();
    38. fish.eat();
    39. goldfish.eat();
    40. return 0;
    41. }
    To copy to clipboard, switch view to plain text mode 

    The output is :-
    I eat like a generic animal.
    I eat like a wolf!
    I eat like a fish!
    I eat like a goldfish!

    Instead of this:-

    I eat like a generic animal.
    I eat like a generic animal.
    I eat like a generic animal.
    I eat like a generic animal.

    Why is this happening? Is there something wrong? If it is possible then what is the use of this virtual function. Please answer me.

    Thank You.
    Last edited by wysota; 23rd May 2012 at 08:00. Reason: missing [code] tags

Similar Threads

  1. Problem with virtual functions
    By eekhoorn12 in forum General Programming
    Replies: 4
    Last Post: 8th April 2010, 13:52
  2. QSharedDataPointer and Data with virtual functions
    By niko in forum Qt Programming
    Replies: 0
    Last Post: 2nd February 2010, 08:23
  3. Replies: 3
    Last Post: 17th February 2009, 04:23
  4. virtual overloaded functions and base class function call...
    By nouknouk in forum General Programming
    Replies: 7
    Last Post: 11th March 2006, 21:26
  5. why triggerUpdate() is not virtual?
    By gadnio in forum Qt Programming
    Replies: 3
    Last Post: 12th January 2006, 15:05

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.