A question regarding convertion constructor
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: A question regarding convertion constructor

  1. #1
    Join Date
    Jul 2005
    Posts
    910

    A question regarding convertion constructor

    Here is the code snippet. In the definition of class Rational, I specified convertion constructor explicit so that I can prevent a int converted implicitly into a Rational object. But to my surprise, when I call Rational r = r1*2, 2 is still converted to a Rational object. Why?
    Code:
    class Rational
    {
    public:
    	Rational(int x = 0, int y = 1)
    	{
    		num = x;
    		den = y;
    	}
    
    	explicit Rational(const int& x)
    	{
    		
    	}
    
    	const Rational& operator*(const Rational& rhs)
    	{
    		num*=rhs.num;
    		den*=rhs.den;
    		return *this;
    	}
    
    private:
    	int num;
    	int den;
    };
    
    
    
    int  main()
    {
    	Rational r1(2, 3);
    	Rational r = r1*2;
    	
    	return 0;
    }

  2. #2
    Join Date
    Oct 2002
    Location
    Austria
    Posts
    1,284

    Re: A question regarding convertion constructor

    Code:
    Rational(int x = 0, int y = 1)
    Because of the default value for y that constructor can convert an int to a Rational.
    Kurt

  3. #3
    Join Date
    Jul 2005
    Posts
    910

    Re: A question regarding convertion constructor

    So constructor Rational(int x = 0, int y = 1) could also be a convertion constructor. It is good to learn. Thanks.
    Quote Originally Posted by ZuK View Post
    Code:
    Rational(int x = 0, int y = 1)
    Because of the default value for y that constructor can convert an int to a Rational.
    Kurt

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center