Dominik
Dominik

Reputation: 93

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.

Upvotes: 7

Views: 880

Answers (1)

LogicStuff
LogicStuff

Reputation: 19607

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).

Upvotes: 15

Related Questions