+ Reply to Thread
Results 1 to 2 of 2

Thread: What is implicit and explicit conversion in C++?

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

    What is implicit and explicit conversion in C++?

    Hi All,

    What is implicit and explicit conversion in C++?

    Thanks

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

    Implicit cast:
    Implicit conversion is you do not need to cast class type to data type.

    Example is:

    Code:
    class CImplicit
    {
    private:
    	int m_nValue ;
    
    public:
    
    	CImplicit(int nValue) : m_nValue (nValue)
    	{
    	}
    
    	int GetValue()
    	{
    		return m_nValue ;
    	}
    } ;
    
    void ImplicitConversion(CImplicit objImplicit)
    {
    	int nValue = objImplicit.GetValue() ;
    }
    
    void UseImplicitConversion()
    {
    	CImplicit objImplicit = 42 ; //here, we do not need to cast int to class type!
    	int nValue = objImplicit.GetValue() ;
    	ImplicitConversion(42) ; //int is automatically cast to CImplicit type!
    }
    Notes:
    a. Implicit conversion is default. You will need to disable it by using 'explicit' keyword as describe in below example.
    b. It works only in the case of single argument constructor.

    Explicit cast:
    When you do not want default implicit cast, user will need to use 'explicit' keyword of C++.

    Example:

    Code:
    class CExplicit
    {
    private:
    	int m_nValue ;
    
    public:
    
    	//disable implicit casting for single arguent, automatic conversion
    	explicit CExplicit(int nValue) : m_nValue (nValue)
    	{
    	}
    
    	int GetValue()
    	{
    		return m_nValue ;
    	}
    } ;
    
    void ExplicitConversion(CExplicit objExplicit)
    {
    	int nValue = objExplicit.GetValue() ;
    }
    
    void UseExplicitConversion()
    {
    	//CExplicit objExplicit1 = 42 ; //error : initializing' : cannot convert from 'const int' to 'class CExplicit'
    	//ExplicitConversion(42) ;//error 'ExplicitConversion' : cannot convert parameter 1 from 'const int' to 'class CExplicit'
    
    	CExplicit objExplicit2(42) ;//works fine
    	int nValue = objExplicit2.GetValue() ;
    }
    In the above case, implicit conversion won't happen as compiler raise an error.

    Tip:
    http://blogs.msdn.com/b/oldnewthing/...24/605974.aspx

+ 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