简体   繁体   中英

C++ calls default constructor instead of copy constructor

I'm trying to write a program for my Arduino, but I don't understand something that's happening when passing an Item object to another Holder object. I've constructed a simple example:

class Item {
  public:
    int property;

    Item() {
      Serial.println("parameterless constructor called");
      this->property = 2;
    }

    Item(int property) {
      this->property = property;
      Serial.println("right constructor called");
    }
};

class Holder {
  public:
    Item someitem;

    Holder(Item& someitem) {
      this->someitem = someitem;
    }
};

void setup() {
  Serial.begin(9600);

  Item someitem = Item(1);
  Serial.println(someitem.property);

  Holder hold = Holder(someitem);
  Serial.println(hold.someitem.property);
}

void loop() {

}

The output on the console is:

right constructor called
1
parameterless constructor called
1

I don't understand why the parameterless constructor is called in the first place (I'm not creating a new object to my understanding), and also why it does neither change the current object nor makes a new one. Leaving out the parameterless constructor is prevented by the compiler.

You forgot how we initialize class members in C++ - member initializer lists :

Holder(Item const& someitem) : someitem(someitem) {}

In your code, someitem is default-constructed first (before execution enters the {} block of the constructor), then you're using assignment operator.

Copy constructor is not invoked (and it can't be on already constructed object).

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