By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,285 Members | 2,147 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,285 IT Pros & Developers. It's quick & easy.

doubt in virtual funtion

P: 52
Hi All,
I am new to c++, please find my program below and my doubt as mentioned below.

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class base
  5. {
  6.     public:
  7.         virtual void Show(void)
  8.         {
  9.             cout << "base:Show" << endl;
  10.             return ;
  11.         }
  12.         void Test(base obj)
  13.         {
  14.             obj.Show();
  15.         }
  16. };
  17. class derived:public base
  18. {
  19.     public:
  20.         void Show(void)
  21.         {
  22.             cout << "derived:Show" << endl;
  23.             return ;
  24.         }
  25. };
  26. int main(int argc, char **argv)
  27. {
  28.     derived d1;
  29.     derived d2;
  30.     d1.Test(d2);
  31.     return 0;
  32. }
  33.  
  34.  

When I call this d1.Test(d2) , its always refers baseclass show funtion( ).Why its refering always base class member funtion. please let me know, what is referring in the backend!
Dec 21 '09 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
The parameter of test has type base. That is it passes an object. What actually happens is the base copy constructor is called to construct a new base object from the derived object d2 that is passed. Inside test since obj has type base it calls base::Show.

I suspect you intended to pass a reference to base into test, base& then when you call test it will pass a base reference to d2 but when you call Show it will call derived::Show because the object is actually a derived object even though it is a base reference.
Dec 21 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.