13

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 references, e.g.

Foo* foo = new Foo();
Foo& bar = foo;
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 1
    `const MixerDevice& const parentMixer` the second `const` is unnecessary since references (unlike pointers) cannot be reseated to reference another object. – Praetorian Jun 23 '12 at 14:57

4 Answers4

21

this is a pointer, to get a reference you have to dereference (*this) it:

MixerLine mixerLine( *this, i );
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
3

You should dereference this, because this is a pointer, not a reference. To correct your code you should write

for(DWORD i=0;i<numLines;i++) {

    MixerLine mixerLine( *this, i ); // Ok, this dereferenced
    // other code here removed
}

Note: the second const at the constructor's parameter const MixerDevice& const parentMixer is completely useless.

Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
1

To obtain a reference from a pointer you need to dereference the pointer, as it has already been mentioned. Additionally (maybe due to copying into the question?) the constructor should not compile:

const MixerDevice& const parentMixer

That is not a proper type, references cannot be const qualified, only the referred type can be, so the two (exactly equivalent) options are:

const MixerDevice& parentMixer
MixerDevice const& parentMixer

(Note that the const qualifying of MixerDevice can be done at either way, and it means exactly the same).

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

Pointer values can be assigned to pointers, but not to references!1

Foo* foo = new Foo();
Foo& bar = *foo;
           ^
           ^


1. Well, they can be used to initialise references-to-pointers, but that's not what you have here...
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680