c/c++ :: conversion constructor

A constructor with only one argument acts like a conversion function. It helps conversion of argument to class type and therefore called conversion constructor.

Example -

class A{ // some class
public:
A(int); // conversion constructor
}

the following are valid, and the conversion constructor is called for each of them

int myint1 = 1, myint2 = 2, myint3 = 3, myint4 = 4;
A a= myint1; // conversion
A b(myint2); // normal constructor using one argument.
A c = A(myint3); // normal constructor using one argument.
c = myint4; // conversion

Note that

A a;

is invalid , but

A a = myint1;

is valid. (Assuming that no A( void ) constructor is there.)

Doubt : Do you observe that constructor is called twice on c in the example above. First normal constructor and then the conversion constructor. Something fishy. Right? What say you ?

Modified : May 18th, 05 : Made more readable, seeing high rank on google search.

One Response to “c/c++ :: conversion constructor”

  1. A.V.Nageswara Rao Says:

    Impressive
    I like this after reading about this article. It is clear to understand and felt good.

Leave a Reply