tags:

views:

141

answers:

3

Example code:

#include <cstdlib>
#include <iostream>
using namespace std;

class A {
public:
    A(int x, int y) : x(x), y(y) {}
    int x, y;
};

class B {
public:
    operator A() {
        return A(x,y);
    }
    float x, y;
};

void func1(A a) {
    cout << "(" << a.x << "," << a.y << ")" << endl;
}

void func2(A *a, int len) {
    for(int i=0; i<len; ++i) {
        cout << "(" << a->x << "," << a->y << ")";
    }
    cout << endl;
}

int main(int argc, char** argv) {
    B b[10];
    func1(b[0]);
    //func2(b, 10);
    return(EXIT_SUCCESS);
}

func1 works as expected, but func2 throws a compile-time error. Is there anything I can add to class B to make this work? I suspect not, but it doesn't hurt to ask, right?

I assume it won't work because the size of A is different from the size of B?

+1  A: 

When you pass array to a method you are only passing the address of the first element not the actual copy of the array nor the first element.

In func1 you pass first element of array which is object of class B. Because B has operator A() it can convert B to A and new object of class A is passed to func1

In func2 you pass pointer to an array of B objects which is not the same as array of A objects so you get error.

To solve it you could have a transformation method that takes pointer to array of B's and iterators over it and for each calls func1 or something like that.

stefanB
I'd like to solve it without using a loop. That I know how to do. But I reckon it's not possible. Thanks
Mark
+5  A: 
void func2(A *a, int len)

When you try to pass a pointer of type B to func2 there is no acceptable conversion from B* to A*. These are two different types from A and B, though the type B has a conversion operator to type A.

AraK
Well that's not really a valid solution. The problem this stems from is that `func2` is part of a 3rd-party library. I'd like `func2` to accept either `A` or `B`. Nevertheless, I guess your paragraph answers it.
Mark
+1  A: 

The other answers have addressed the core issue. But for completeness, it's worth noting that

I assume it won't work because the size of A is different from the size of B?

is incorrect.

First, A and B as given in this example would actually be the same size on many current compilers.

But even when A and B are the same size, the compiler will not perform this kind of conversion automatically. In fact, even if they have the exact same memory layout of member variables, the compiler will still not do it.

TheUndeadFish
Well, my logic was that it wouldn't accept this because then the pointer arithmetic wouldn't (necessarily) work. It would try to operate as though it were an A, even though it's a B.
Mark