Monday, August 20, 2007

Explicit Constructors

What is Explicit Constructors ?
Explicit constructors are simply constructors that cannot take part in an implicit conversion.Then what is implicit conversion , this i could not understand ? ok i will write an example and explain.
Class Base
{
public: Base(int x) { size=x;
}
Base(const Base&)
{
std::cout << "Base::Base(const Base&)" << std::endl;
}
};
void useBase(const Base & aBase)
{
}
int main()
{
//Direct constructor call
Base myObj(123);

// equivalent to bb = Base(123);
Base bb = 123;//implicit conversion

// equivalent to useBase(Base(123) )
useBase(123);//implicit conversion
}

The above program gets compiled and worked fine. But the problem is here the implicit conversion happes.So here we got to know one thing that "For a single argument constructor, C++ by default also defines an implicit conversion."
Is not it? Yes Boss...
Because the implicit conversion involves calling the Base constructor, so enough storage is being allocated for a new Base object,
needless to say the memory reserved for 123 elements contained in the Base. Surely this is not what we intended! ?
Am i correct?
Now i explain the above programm.Befor start explaining the program, i just want to discuss 2 important aspect right now.

1)Explicit syntax

2)Assignment syntax

what are these ?

Explicit syntax
See when we write T t(v) ,here T is type means class name small t is object of that type and v is the argument of some type V which will be initialised by calling the constructor T::T(V v) .

Assignment syntax
T t = v;
For the above statement, the compiler will generate code that is equivalent with the following sequence of steps.
If necessary, i.e. if v(here v is 123 if you take my above example) is not of type T, convert v to a temporary T object
tmp_t. Initialize t using the copy constructor T::T(const T&) with tmp_t
as argument.

In most cases, the compiler may optimize in such way that the effect of the assignment syntax is the same as that of the explicit syntax. This is the case, e.g. if there exists a (non-explicit) constructor T::T(V) (see my the example), where we assume that v has type V.
*************************************************************************
Base bb = 123;

Here the compiler optimized away the call to the copy constructor of Base ,
by directly applying the convertor/constructor Base::Base(int) to bb object.

if write Base bb = 123; it means Base(123) , that is why it is implicitly converted. Same is the case if call useBase(123)
I think it is clearlly understood..... if there is any doubt pls let me know.
Cheer,
sahu
hara.sahu@gmail.com

No comments: