doubt in virtual funtion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sridhard2406
    New Member
    • Dec 2007
    • 52

    #1

    doubt in virtual funtion

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

    Code:
    #include <iostream>
    using namespace std;
    
    class base
    {
        public:
            virtual void Show(void)
            {
                cout << "base:Show" << endl;
                return ;
            }
            void Test(base obj)
            {
                obj.Show();
            }
    };
    class derived:public base
    {
        public:
            void Show(void)
            {
                cout << "derived:Show" << endl;
                return ;
            }
    };
    int main(int argc, char **argv)
    {
        derived d1;
        derived d2;
        d1.Test(d2);
        return 0;
    }

    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!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    Working...