I tried adding const to the copy-constructor, but it does not work
either (although there is another error message now:
myVector.cpp: In copy constructor `myVector::myVector(const
myVector&)':
myVector.cpp:34: error: passing `const myVector' as `this' argument of
`int myVector::size()' discards qualifiers
I guess this is because I am using an instance-method of the
to-be-copied-object in the copy constructor...
> Probably you are trying to copy a constant object, but by your declaration,
> you told the compiler that the original object gets modified by your copy
> constructor.
It is true that I would like change the original object by this method.
But this should be no mistake as such shouldn't it? Strings can do
exactly the same. Thus, what I need should also be implemented in the
std::string class because you can say:
string s1("ladida");
string s2("testing"); and then
s1 = s1 + s2;
thanks a lot for your help..
Tim
Rolf Magnus schrieb:
> silversurfer2025 wrote:
>
> > Aah, OK, so it is save to give back "result" because it is copied.
> > Thanks for the info, I think that I got it now (giving back references
> > and pointers to local variables is the problem, not giving back the
> > objects themselves... thanks! Finally came the general insight! Thanks
> > for that).
>
> Yes, that's right.
>
> > If the local object is copied by returning it from the method, do I
> > need to write a copy-constructor as well?
>
> Only if you want to do something else than the compiler-generated copy
> constructor would do. It does a memberwise copy of the object.
>
> > I am getting athe following compiler-error from this line in the mai()
> > method:
> > myVector r = fv1 + fv2;
> >
> > error:
> > main.cpp:123: error: no matching function for call to `myVector::
> > myVector(myVector)'
> > myVector.h:26: error: candidates are:
> > myVectorr::myVector(myVector&)
> >
> >> What's that supposed to mean?
>
> Probably you are trying to copy a constant object, but by your declaration,
> you told the compiler that the original object gets modified by your copy
> constructor. Try to declare it as:
>
> myVector::myVector(const myVector&)
>
> >> > myVector result;
> >> > //add elements here,...
> >> > return result;
> > This was just a way to let everything be shorter.. It should have only
> > shown that I have a myVector object within the method, then change this
> > object and give it back in the end.
> >
> >> The above operator doesn't use any pointers or references.
> > I know, I merely thought of using them because I thought that I could
> > not return a local variable.
>
> It's just the other way round, but you already know that now