0

So I m creating two classes A and B and I want to practice type casting. So in this this example

I m creating 2 variables , 'foo'(class A type) and 'bar'(class B type) in the stack and when casting from B TO A using 'foo = bar;' I m creating new variable in the Heap and p pointer to it I want my variable 'foo' to point to that variable.I m doing that right ?? and how do I check if everything is working fine ( the value of foo has changed to 7 ) you can view the code and tell me more about what's going on and is it possible to let foo point to the pointer or not??

class A {
    public:
    int a;
    A(int x)
    {
        a = x;
    }
};

class B {
public:
    int x;
  // conversion from A (constructor):
  B(int a)
  {
    x=a;
  }
 // B (const A& x) {cout<<"conversion done"<<endl;}
  // conversion from A (assignment):
  B& operator= (const A& c) {this->x =c.a ;return *this;}
  // conversion to A (type-cast operator)
  operator A() {
    cout<<"typecast"<<endl;
   A *p = (new A(x));
   cout<<p<<endl;
   return *p;
   }
};

int main ()
{
  A foo(5);

  cout<<&foo<<endl;

  B bar(7);

  foo = bar;   
     
  cout<<&foo<<endl;

  return 0;
} ```

the output: 

0x5b73fff75c
typecast
0x201cdfc1580
0x5b73fff75c

Sor3a
  • 3
  • 2

0 Answers0