Virtual functions, confusion

This is a discussion on Virtual functions, confusion within the C++ Programming forums, part of the General Programming Boards category; I am trying to understand the sense of virtual fuctions and so I wrote the following piece of code: Code: ...

  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
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,270
    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, 09:45 PM
  3. virtual functions
    By lord in forum C++ Programming
    Replies: 9
    Last Post: 10-18-2008, 03:55 PM
  4. Virtual Functions
    By vb.bajpai in forum C++ Programming
    Replies: 3
    Last Post: 06-23-2007, 01:38 PM
  5. Virtual functions but non-virtual destructor
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2007, 12:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21