top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is conversion constructor in C++?

+2 votes
638 views
What is conversion constructor in C++?
posted Mar 28, 2014 by Simranjeet Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

In C++, if a class has a constructor which can be called with a single argument, then this constructor becomes conversion constructor because such a constructor allows automatic conversion to the class being constructed.

Example

class Test 
{
 private:
   int x;
 public:
   Test(int i) {x = i;}
   void show() { cout<<" x = "<<x<<endl; }
};

int main()
{
 Test t(200);
 t.show();
 t = 300; // conversion constructor is called here.
 t.show();
}

The above program prints:

x = 200
x = 300
answer Mar 28, 2014 by Luv Kumar
0 votes

Constructor which is called with single argument used for converting from the type of the argument to the class type is called conversion constructor.

answer Apr 2, 2014 by Karan Joglekar
...