Deqing
Deqing

Reputation: 14632

Can I convert a pointer to my class?

I'm refactoring a class for my project to adapt int data. The code is quite complicated, try to give a simple example below:

struct A {
  A(int a):a_(a) {}  // Supports implicit conversion from int
  int a_;
};

void print(A a) { cout<<a.a_<<endl; }

void x2(A *a) {   // change a's value
  a->a_ *= 2;
}

int main() {
  int b = 2;
  print(b);      // pass int as A without any problem
  x2(&b);        // pass int* as A* - failed
  cout<<b<<endl; // b is supposed to changed by x2()
}

In this case maybe template is a good choice, but I'm afraid rewritting the whole class with template would be a huge effort and would do a little harm to the readablity especially for my colleagues.

Is there any other way to use "int*" as "A*"?

Upvotes: 0

Views: 81

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

No, there's no "way". What you are trying to do here is violating the contract on x2, which is that a will be a valid pointer to A.

The simplest change to it would be to change x2 to: (There's really no need to use a pointer here)

void x2 (A& a) {
    a.a_ *= 2;
}

And then call it with A value that's wrapped around the int (like @jrok suggested):

A a(2);
x2(a);

If you are conderned with printing, provide operator<< for A.

Upvotes: 2

Related Questions