0

What will happen if we increment a pointer to class which is typecasted to int type?

#include<bits/stdc++.h> 
using namespace std;
class Hello{
   int x=2;
   int y=3;
 public: 
    void print(){
      cout<<"This is class Hello";
    }
};
int main() {
Hello *h=new Hello();
int *i=(int *)h;
    i++;  //What will i point to?   
}


My question is what does i point to once incremented as shown in the above code?

Also I have another doubt-I know memory to a structure in contigious fashion,Is memory assigned in contigious manner to class?
P.S:This question was asked to me in an interview with Toshiba Software

user7098526
  • 235
  • 3
  • 8

2 Answers2

2

Semi official answer: this is undefined behavior, and anything the program does after the increment is fair game. Seriously, anything.

If you do this, run your program and it hacks your bank account, that's okay. It's not violating the way you wrote it.

There is one complication, though. The lives up to the definition of "PoD", or "Plain ol' data" (full definition in the link). Such structs are guaranteed to be layed out like C structs. With that in mind, you will likely get it pointing to y as you expect, and can even claim that's within the language's specs.

With that said, why #@$&!(@# would you do such a thing? If you two distinct things to reside in the same memory location, use a union.

Shachar Shemesh
  • 8,193
  • 6
  • 25
  • 57
  • Strictly speaking, if the compiler can prove the bad code is reached, anything the program does *before* is UB as well. – StoryTeller - Unslander Monica Sep 14 '17 at 14:08
  • The definition of PoD does not, as far as I know, include private members as a criteria. I linked to it in the answer. – Shachar Shemesh Sep 14 '17 at 14:10
  • Yeah, yeah. I deleted my comment for that reason. So long as all data members have the same accessibility level, even private, then accessibility won't be a problem. – StoryTeller - Unslander Monica Sep 14 '17 at 14:13
  • I understand why for virtual methods, because of the vtable pointer, but how does it change the layout of the structure if it has a constructor or static member? Static members I thought were in the same memory space as global static members. And the constructor method isn't part of the structure, is it, I mean as far as occupying part of the size of the struct. – Zebrafish Sep 14 '17 at 14:34
  • It was a copying error. Read the definition at the link. – Shachar Shemesh Sep 14 '17 at 17:31
1

This is an undefined behavior.

In practice, the new i will point four bytes (sizeof(int)) past the beginning of the allocated instance of Hello and has many chances to point to Hello.y.

This class indeed probably be allocated contiguously. In other cases, alignment constraints can be enforced and result in padding between fields.

  • You shouldn't ask such a question here as many respondents hate them. And I shouldn't be answering. ;-) –  Sep 14 '17 at 14:10