0
#include<iostream>
using namespace std;

class Child {
public:
    int b;
    void gotoSchool() {
        cout << "going to school";
    }
};

int main( )
{
    int a; 
    Child *p2 = (Child *) &a;  // #2
    p2->gotoSchool();

    return 0;
}

The output of this code is

going to school

but how is this working? How can an integer be typecasted to a user-defined class? Explain to me the concept behind this scenario, please.

Student
  • 805
  • 1
  • 8
  • 11
jefe23984
  • 69
  • 1
  • 7

1 Answers1

0

What you are doing there is just casting an address and not an integer. For your computer an integer is a serie of bytes (4 bytes in a 32bits processor), let's put it a value of 8. This integer has an address (4 bytes in a 32bits processor too), let's say that the value of that address is 1.

In your code you are casting the address of a. So, pointer p2 has its address. A pointer is an address by definition. The arguments that your class "Child" will take in the casting are the byte values after "a" until it fills its data. In this case, the data is a single int, so the value of "a" and the value of Child "b" is going to be the same one. A pointer as it is just a memory address can be whatever type (consider a class a type you want). The type only tells to the pointer what is the size of the data, and how to interpret it. Now you have been unlucky and the type fits perfectly with the integer. But usually the behaviour of such casting is unespected. I have modified your code in order to ilustrate what is happening, I think you will see it much more clear after executing it

#include<iostream>

using namespace std;


class Child {


public:
  float b;
  Child(){ b = -0.5;};
  void gotoSchool(){
  cout<<"going to school" << endl;}
  void changeValue(){ b = -0.5;};
  void displayB()
  {
     cout << "the value of b is " << b << endl;
  };
};

class OriginalChild {
public:
   int b;
   void gotoSchool(){
   cout<<"going to school";}
};

int main( )
{
  int a = 8;
  Child *p2 = (Child *) &a;  // #2
  OriginalChild *p3 = (OriginalChild *) &a;
  p2->gotoSchool();

  cout << a << endl;
  p2->displayB();
  cout << p3->b << endl;

  p2->changeValue();
  cout << a << endl;
  return 0;
}