+ Reply to Thread
Results 1 to 2 of 2

Thread: Implement virtual function in C. How?

  1. #1

    Implement virtual function in C. How?

    Implement virtual function in C. How?

    Please provide me some good example.

  2. #2
    Following is the example code:

    Code:
    struct MyVirtual ;
    
    struct VTable
    {
    	void (*pfnCallMe) (struct MyVirtual *pThis, char szData[]) ;
    
    	void (*pfnDisplayMessage) (struct MyVirtual *pThis) ;
    } ;
    
    struct MyVirtual
    {
    	char szData[100] ;
    	struct VTable *vfptr ;
    } ;
    
    void Init_MyVirtual(struct MyVirtual *pThis) ;
    void CallMe_MyVirtual(struct MyVirtual *pThis, char szData[]) ;
    void DisplayMessage_MyVirtual(struct MyVirtual *pThis) ;
    
    
    struct VTable objVTable = { CallMe_MyVirtual, DisplayMessage_MyVirtual } ;
    
    
    void Init_MyVirtual(struct MyVirtual *pThis)
    {
    	pThis->vfptr = &objVTable ;
    }
    
    void CallMe_MyVirtual(struct MyVirtual *pThis, char szData[])
    {
    	strcpy(pThis->szData, szData) ;
    }
    
    void DisplayMessage_MyVirtual(struct MyVirtual *pThis)
    {
    	OutputDebugString(pThis->szData) ;
    }
    
    void UseVirtualInC()
    {
    	struct MyVirtual objMyVirtual ;
    
    	//this is like a constructor... 
    	Init_MyVirtual(&objMyVirtual) ;
    
    	//assign some data to class member
    	objMyVirtual.vfptr->pfnCallMe(&objMyVirtual, "Hello World to C virtual function!!!") ;
    
    	//use assigned data...
    	objMyVirtual.vfptr->pfnDisplayMessage(&objMyVirtual) ;
    }
    Hope this helps you.

+ 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