From what I understand, assignment uses the operator=
function, and initialization uses the contsructor. But when you assign another object during declaration, what happens? I would have thought that car2
would initialize with car1
's data, but I can't tell. Does it initialize with the default constructor first, and then re-assign the data? I tried writing a quick program and traced it with a debugger, but it wouldn't let me look through the important line Car car2 = car1
. I've included my program below.
#include <iostream>
#include <string>
class Car
{
public:
Car();
Car(std::string color, std::string make);
private:
std::string color;
std::string make;
};
Car::Car() {
this->color = "None";
this->make = "None";
}
Car::Car(std::string color, std::string make) {
this->color = color;
this->make = make;
}
int main() {
Car car1("blue", "Toyota");
Car car2 = car1;
return 0;
}
Car
has an implicitly declared copy-ctor , which is used here as the ctor-call cannot be elided (it is not initialized with a pr-value), nor is move-construction possible (it is not an xvalue).
That implicitly-declared copy-ctor does member-wise copy-construction.
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.