C++ Passing `this` into method by reference
- by David
I have a class constructor that expects a reference to another class object to be passed in as an argument. I understand that references are preferable to pointers when no pointer arithmetic will be performed or when a null value will not exist.
This is the header declaration of the constructor:
class MixerLine {
private:
MIXERLINE _mixerLine;
public:
MixerLine(const MixerDevice& const parentMixer, DWORD destinationIndex);
~MixerLine();
}
This is the code that calls the constructor (MixerDevice.cpp):
void MixerDevice::enumerateLines() {
DWORD numLines = getDestinationCount();
for(DWORD i=0;i<numLines;i++) {
MixerLine mixerLine( this, i );
// other code here removed
}
}
Compilation of MixerDevice.cpp fails with this error:
Error 3 error C2664: 'MixerLine::MixerLine(const MixerDevice &,DWORD)' : cannot convert parameter 1 from 'MixerDevice *const ' to 'const MixerDevice &'
But I thought pointer values could be assigned to pointers, e.g.
Foo* foo = new Foo();
Foo& bar = foo;