Scott
Scott

Reputation: 455

Pointer confusion c++

I have the following practical work to complete to learn c++, I've been spending a long time looking for an answer and reading through all my work but I'm a bit confused could I get clarification of where I am going wrong here. The code looks like below:

SafeArray& SafeArray::operator =(const SafeArray& other) {
//Add code here
return *this;
}

We have to implement code that assigns one array to another. Now if I understand that code correctly the method takes a formal parameter of a constant "SafeArray" called other. The & after the SafeArray means that the actual array itself is passed and not a copy while const means that it can not be changed. Similarly the method returns the actual array itself and not a copy of it.

As such I thought that this would be a simple case of creating a pointer, referencing the memory location of "other" and then returning the de-referenced result. In my attempts to actually code this thought I've had no luck.

I tried doing something like the following:

SafeArray* ptr = &other; //This should have created a SafeArray pointer to the memory location of the array "other".

The problem here is that I get the error:

main.cpp:31:23: error: invalid conversion from ‘const SafeArray*’ to ‘SafeArray*’ [-fpermissive]

I guess the reason for this is that I am trying to convert something I'm not allowed to alter into something I can.

I can write the code like this:

const SafeArray* = &other;

But then I can't return the value properly either. I'm clearly misunderstanding something here theoretically I presume, could someone please explain what I am missing. I'm more than happy to work the coding out myself but I can't quite grasp this method call.

Upvotes: 2

Views: 133

Answers (1)

Benoît
Benoît

Reputation: 16994

To correctly define this operator, you simply have to copy the contents of your SafeArray object other passed as parameter into this.

The only way to know how to complete this function is to understand the contents, ie data members, of the SafeArray class.

Upvotes: 1

Related Questions