943,948 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 708
  • C++ RSS
Sep 17th, 2008
0

virutual function

Expand Post »
hi
what is the purpose of virtual function, please give me idea



thanks
bala
Reputation Points: 10
Solved Threads: 0
Newbie Poster
balakrishnan.kb is offline Offline
24 posts
since Aug 2008
Sep 17th, 2008
0

Re: virutual function

you can find loads of examples-definitions on google.. go through them.. then when you have more specific doubts ppl here can help .. happy learning
Featured Poster
Reputation Points: 431
Solved Threads: 116
Practically a Master Poster
Agni is offline Offline
654 posts
since Dec 2007
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Sep 17th, 2008
1

Re: virutual function

Virtual functions are the backbone of runtime polymorphism. You can use a member function declared as virtual to redefine the behavior of a base class. Then, when accessing a derived class through a pointer or reference to the base class, the redefined member function will be called:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2.  
  3. class base {
  4. public:
  5. virtual void foo() const { std::cout<<"base\n"; }
  6. };
  7.  
  8. class derived: public base {
  9. public:
  10. virtual void foo() const { std::cout<<"derived\n"; }
  11. };
  12.  
  13. void do_foo ( const base& b )
  14. {
  15. b.foo();
  16. }
  17.  
  18. int main()
  19. {
  20. do_foo ( base() ); // Call 1
  21. do_foo ( derived() ); // Call 2
  22. }
This works because in do_foo, b has two types. The static type is the type of object the code says the reference refers to (base in all cases). The dynamic type is the type of object the reference actually refers to (base in call 1, derived in call 2).

The virtual mechanism is a way to access the dynamic type safely and easily.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: determinant 'pow'
Next Thread in C++ Forum Timeline: Arrays (Reading in 10 numbers)





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC