tags:

views:

109

answers:

4
#include <iostream>
using namespace std;
struct testarray{
    int element;
public:
    testarray(int a):element(a){}
};
class myarray 
{ 
public:
    testarray i; 

    public: 
            myarray(testarray a) : i(a){ } 


} ;
int main()
{
    myarray objArray[3] = {1,2,3};

    return 0;
}

The above code compiles fine in Visual C++ 2005 Express Edition IDE. But what I want is to prevent the compiler from implicitly typecasting the object type.

+9  A: 

Use the keyword explicit for testarray constructor so that the compiler doesn't perform implicit conversions. Basically you need to write the constructor as:

explicit testarray(int a):element(a){}
Naveen
More generally, always write constructor that can be invoke with a single parameter (taking default values into account) as `explicit`. And evaluate carefully if can take the `explicit` out before removing it, it might save some typing but it WILL introduce bugs :)
Matthieu M.
A: 

Perhaps you want the constructor to be explicit?

http://www.cppreference.com/wiki/keywords/explicit

alex tingle
+4  A: 

You can use explicit keyword for your struct constructor.

SMART_n
+1  A: 

yes, use the keyword "explicit" as stated above. one more suggestion about the source you've provided: why do you have the "public" in the struct? All struct's members are public by default. if you want to have smth with different access modifiers (say, several "private" members or methods), you're better off to use classes.

varnie
thanks for the observation code was written purely written for experimental purpose but i understand that still i should have coded it neatly.
pushkarpriyadarshi