Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Dominik Avatar asked Dec 18 '15 13:12

Dominik


Video Answer


1 Answers

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

like image 122
LogicStuff Avatar answered Oct 05 '22 09:10

LogicStuff