0

Let's say I have a class PArr which stores an array of various classes StringWrapper, FloatWrapper, IntWrapper- all of them derive from a base class Wrapper.

It's PArr class:

class PArr{
private:
    Wrapper** _wrappers;
    int _size;
public:
    PArr(int size);
    Wrapper& operator[](int index);


};

And here's the implementation of this class

#include "PArr.h"

PArr::PArr(int size){

    _size = size;
    _wrappers = new Wrapper*[_size];

}

Wrapper& PArr::operator[](int index){

    return _wrappers[index];
}

And here's the class for example FloatWrapper

#pragma once
#include "Wrapper.h"

class FloatWrapper : public Wrapper{
private:
      float* _floatPtr;
public:
      FloatWrapper(float number);

};   

My main method looks like this:

int main() {  
     PArr a(3);

     a[0] = new FloatWrapper(0.1);
}

I get an error: "no match for 'operator=' (operand types are 'Wrapper' and 'FloatWrapper*')

What am I doing wrong?

2
  • The implementation of the class will also not compile. The operator[] returns a Wrapper &, but _wrappers[index] is of type Wrapper *. The mistake you're making is assuming that references and pointers are interchangeable. They are not. Commented Mar 5, 2019 at 20:30
  • If my answer was helpful, or perhaps even correct, it'd be nice if you marked it as an accepted answer, upvoted it or both. If it wasn't any good, you should say so and maybe it'll get improved. Commented Mar 7, 2019 at 19:54

1 Answer 1

2

At the risk of stating the obvious: your operator[] is returning a Wrapper&, which is a reference type, and you're trying to assign a Wrapper*, a pointer type to it. This ain't gonna work.

If you rewrote your main function slightly, say like this:

int main()
{  
  PArr a(3);
  auto k = a[0];
}

you might find the error more informative:

main.cpp: In member function 'Wrapper& PArr::operator[](int)':

main.cpp:27:27: error: invalid initialization of reference of type 'Wrapper&' from expression of type 'Wrapper*'

return _wrappers[index];

       ~~~~~~~~~~~~~~~^

You might try something like this instead:

Wrapper*& PArr::operator[](int index)
{
  return _wrappers[index];
}

which does compile and let your original main run, at least for me. I make no further promises.

Finally, this answer isn't the place to go into the deeper problems with your code (use smart pointers, use standard library container classes like array or vector, consider things like std::any or std::variant), but, y'know, you should read up on those things.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.