+ Reply to Thread
Results 1 to 2 of 2

Thread: Can I call virtual function from constructor?

  1. #1

    Can I call virtual function from constructor?

    Can I call virtual function from constructor?

    Is it safe to to do this?

    Thanks.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    As per below example, you can call virtual function from the constructor.

    But it is advisable to not to call virtual function from constructor. A you can see that in below example, CVirtualCall's constructor call's its own implemented DisplayMessage method rather than CDerivedVirtualCall :: DisplayMessage!

    Example:

    Code:
    class CVirtualCall
    {
    public:
    	CVirtualCall()
    	{
    		DisplayMessage() ;
    	}
    
    	virtual void DisplayMessage()
    	{
    		OutputDebugString("Hello from CVirtualCall::DisplayMessage\n") ;
    	}
    } ;
    
    class CDerivedVirtualCall : public CVirtualCall
    {
    public:
    	CDerivedVirtualCall()
    	{
    		 DisplayMessage() ;
    	}
    
    	virtual void DisplayMessage()
    	{
    		OutputDebugString("Hello from CDerivedVirtualCall::DisplayMessage\n") ;
    	}
    } ;
    
    void UseVirtualCall
    {
            CVirtualCall objVirtualCall ;
    	CDerivedVirtualCall objDerivedVirtualCall ;
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts