+ Reply to Thread
Results 1 to 2 of 2

Thread: What is virtual function?

  1. #1

    What is virtual function?

    Hi,

    What is virtual function in C++?

    How to use it?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    When we call a function using class object, it is static binding without using virtual keyword.

    When a function is declared with 'virtual' keyword and the derived class can implements that method.
    At run-time, compiler will decide what method to be executed based on the the type of the object it points to.

    Example:

    Code:
    class CBase
    {
    private:
    public:
    	CBase()
    	{
    	}
    
    	void DisaplyMessageWithoutVirtual()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "CBase::DisaplyMessageWithoutVirtual") ;
    		printf(szMessage) ;
    	}
    
    	virtual void DisaplyMessageWithVirtual()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "CBase::DisaplyMessageWithVirtual") ;
    		printf(szMessage) ;
    	}
    } ;
    
    class CDerived : public CBase
    {
    private:
    public:
    	CDerived()
    	{
    	}
    
    	void DisaplyMessageWithoutVirtual()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "CDerived::DisaplyMessageWithoutVirtual") ;
    		printf(szMessage) ;
    	}
    
    	virtual void DisaplyMessageWithVirtual()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "CDerived::DisaplyMessageWithVirtual") ;
    		printf(szMessage) ;
    	}
    } ;
    
    void UseVirtual()
    {
    	CBase objBase ;
    
    	//this prints "CBase::DisaplyMessageWithVirtual"
    	objBase.DisaplyMessageWithVirtual() ;
    
    	CDerived objDerived ;
    
    	//this prints "CDerived::DisaplyMessageWithVirtual"
    	objDerived.DisaplyMessageWithVirtual() ;
    
    
    	CBase *pDerived = new CDerived() ;
    
    	//this prints "CBase::DisaplyMessageWithoutVirtual"
    	pDerived->DisaplyMessageWithoutVirtual() ;
    
    	//Wow, this prints "CDerived::DisaplyMessageWithVirtual"
    	//This is because of the 'virtual keyword!
    	pDerived->DisaplyMessageWithVirtual() ;
    }
    Regards.

+ 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