Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Passing `this` into method by reference

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;
like image 740
Dai Avatar asked Jun 23 '12 14:06

Dai


People also ask

What is pass-by-reference method?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

Is C language pass by value or reference?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.

How arguments are passed to a function using references in C?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

What is pass by value and pass-by-reference in C?

"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.


1 Answers

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

MixerLine mixerLine( *this, i );
like image 71
Yakov Galka Avatar answered Oct 30 '22 01:10

Yakov Galka