+ Reply to Thread
Results 1 to 2 of 2

Thread: What is C-Style casting?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    29

    What is C-Style casting?

    Hi All,

    What is C-Style casting?

    Regards.

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

    Have a look at below code fragment:

    Code:
    struct Student
    {
    	int nRoleID ;
    	char szName[100] ;
    } ;
    
    void UseCStyleCasting()
    {
    	int nValue = 10 ;
    
    	//C-Style casting, convert int to float...
    	float fValue = (float) nValue ;
    
    	Student objStudent ;
    	objStudent.nRoleID = 10 ;
    	strcpy(objStudent.szName, "Hemen") ;
    
    	//C-Style casting, convert struct type to void *
    	void *pAnything = (void *) &objStudent ;
    
    	//C-Style casting, convert void * back to struct type
    	Student *pStudent = (Student *) pAnything ;
    }
    Notes:
    a. Please note that it is not recommended to use C-Style casting in C++.
    b. Always use casting mechanism provided by C++ whenever possible, like static_cast, dynamic_cast, const_cast etc...
    c. C++ style casting is more type safe.
    d. C++ style casting is more safe at run-time as well.

+ 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