5 years, 12 months ago.  This question has been closed. Reason: Answered

Question about C++ objects

Looking at the constructor code for an I/O expander library:

MCP23S17::MCP23S17(SPI& spi, PinName ncs, char writeOpcode) : _spi(spi), _ncs(ncs) {

I can pass the constructor a "SPI" port instance and the line _spi(spi) appears to store the SPI object so that "_spi" refers to the port in question but:

Does "_spi(spi)" create a reference to the same object or does it create a second SPI object assigned to the same port. I'm thinking it might be the latter as it seems to be calling a constructor.

2 Answers

5 years, 12 months ago.

The syntax you're seeing is called "(member) initializer list". It is basically equivalent to the following:

MCP23S17::MCP23S17(SPI& spi, PinName ncs, char writeOpcode) {
  _spi = spi;
  _ncs = ncs;
  ...

And you can see that _spi member is a reference:

protected:
    SPI& _spi;

So in this case there's no constructor involved, only the reference is being assigned.

I think I get it... the & indicates its a reference?

so in the case of _ncs it is not a reference as the member was declared without the leading & and the ncs parameter is of type PinName but _ncs is of type DigitalOut.

posted by Oliver Broad 21 Oct 2013

Yes, for _ncs an actual constructor is invoked.

posted by Igor Skochinsky 21 Oct 2013
5 years, 12 months ago.

the argument 'spi' is passed as reference to the ctor and the "_spi(spi)" means, that there is an attribute in the base class that is initialized also with 'spi'. The "_spi(spi)" does not create a reference, the reference is passed - this makes a difference. The only instance of 'spi' that really exists, is the one you create in your own code. The MCP23S17 ctor and the _spi() attribute only see the reference to this instance. Image a book in a library - that's your 'spi' object's instance. This book is in your code. Now you create a piece of paper (=the reference) and note where to find this book (room 4, rack 7, position 11). Instead of giving the book away, you only pass the piece of paper to the constructor, but the constructor also uses this piece of paper and tells "_spi" where to find the book.