Thread: Virtual functions, confusion

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    19

    Virtual functions, confusion

    I am trying to understand the sense of virtual fuctions and so I wrote the following piece of code:
    Code:
    #include <iostream>
    using namespace std;
    
    class Base
    {
    public:
    	virtual void doit() { cout << "Base" << endl; }
    };
    
    class Derived : public Base
    {
    public:
    	virtual void doit() { cout << "Derived" << endl; }
    };
    
    int main()
    {
    	Base b;
    	Derived d;
    
    	Base &reference = b;
    	reference.doit();
    	reference = d;
    	reference.doit();
    }
    When I compile it, I get:
    Code:
    Base
    Base
    Why? Shouldn't the second call return "Derived"?

    Conversely, when I write:
    Code:
    int main()
    {
    	Base b;
    	Derived d;
    
    	Base &reference = d;
    	reference.doit();
    	reference = b;
    	reference.doit();
    }
    It returns:
    Code:
    Derived
    Derived
    What is the point of the virtual functions if by re-assigning the reference to a different type, it still uses the old function?

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    You can't re-assign a reference. The "reference = b" line invoked the base class assignment operator, i.e. performed a wrong behavior. You can't change the object a reference refers to. Use a pointer instead.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Virtual functions
    By SterlingM in forum C++ Programming
    Replies: 12
    Last Post: 11-03-2009, 11:51 AM
  2. relative virtual addresses confusion
    By MrNoobah in forum Windows Programming
    Replies: 7
    Last Post: 10-13-2009, 08:45 PM
  3. virtual functions
    By lord in forum C++ Programming
    Replies: 9
    Last Post: 10-18-2008, 02:55 PM
  4. Virtual Functions
    By vb.bajpai in forum C++ Programming
    Replies: 3
    Last Post: 06-23-2007, 12:38 PM
  5. Virtual functions but non-virtual destructor
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2007, 11:08 AM