Reputation: 4406
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)
Upvotes: 1
Views: 173
Reputation: 1092
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.
Upvotes: 0
Reputation: 1698
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
Upvotes: -1
Reputation: 55897
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.
Upvotes: 4