Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
11 years, 2 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
11 years, 2 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.
11 years, 2 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.