Can I create an array this way?

Sample 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 the class B

to make this work? I suspect not, but it doesn't hurt to ask, right?

I am guessing it won't work because the size A

is different from the size B

?

+2


source to share


3 answers


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

In func1

you pass the first element of the array, which is an object of class B. Since B has operator A()

, it can convert B

to A

, and the new object of the class A

is passed tofunc1



In func2

you are passing a pointer to an array of B objects that is not the same as the array of A objects, so you get an error.

To solve this problem, you can have a conversion method that takes a pointer to an array of B and iterators over it and for each call func1

or something like that.

+1


source


void func2(A *a, int len)

      



When trying to pass a type pointer B

to a func2

valid conversion from B*

to, there is A*

no valid conversion . They are two different types from A

and B

, although the type B

has a conversion operator for input A

.

+5


source


The other answers have touched on the main question. But for the sake of completeness, it is worth noting that

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

wrong.

First, A and B in this example will actually be the same size for many modern compilers.

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

+1


source







All Articles