简体   繁体   中英

C++ operator overloading weird type conversion

I have simple c++ class vector and it has parameter constructor as follow:

Vector::Vector(int size){
   ...
}

Based on this implementation following lines are valid:

Vector v(1);
Vector v2(94);

My question is I was testing my code and I came across this was also valid:

Vector v = 1;

which called parameter constructor somehow. I also overloaded operator = but in this case it was never called. Is this normal behavior in c++? How does a compiler treat above assignment as Vector v(1) ? I'm doing this in Xcode 5.0 (LLVM compiler)

It's not overloaded operator = , it's copy-initialization. If you want prevent such construction of vector, then you can use explicit constructor.

explicit Vector(int);

now

Vector v = 1;

is incorrect.

This happens due to 'Automatic Type Conversion' that compiler supports quietly. That's why it works with no copy constructor.

Bruce Eckel tells in his book "Thinking in C++":

The default constructor, copy-constructor, operator= and destructor can be synthesized automatically by compiler.

The following , x2 would call copy constructor in x2 = x1 ;

ClassX  x1() ;
ClassX  x2 =  x1 ;

The following , x4 would call copy assignment in x4 = x3 ;

ClassX  x3() ;
ClassX  x4() ;
x4 = x3 ;

If ClassX has explicit in copy construtor , then

ClassX x5(x1) ;  //this will compiled ok 
ClassX x5 = x1 ; //This will fail while compiled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM