0

i am having little trouble with class and object.i have this code and i just incementing the address of its object but no matter how many times i increment it is still able to access the member function .please help me i dont get this what i think is it is not suppose to happen?

#include<iostream>
using namespace std;
class B
{
int a,d,b,c;
public:
 void cl()
   {
     int f,m,b;
    cout<<"\nvoid cl";
   }
} obj;

int main()
{  B *m;

  int *i;
  m=&obj;
  cout<<"\nsize of obj="<<sizeof(obj);
  cout<<"\naddress of obj "<<&obj;
  cout<<"\nvalue of m="<<m;
  i=new int;
 // for(int j=0;j<10;j++)
  cout<<"\n value of i "<<*i;
  for(int j=0;j<10;j++)
{ m++;
  cout<<"\nvalue of m++ "<<m++;
  m->cl();
} cout<<"\n";
}

and the output is

nik-pc@nik:~/Documents$ ./a.out 

size of obj=16
address of obj 0x6013e0
value of m=0x6013e0
 value of i 0
value of m++ 0x6013f0
void cl
value of m++ 0x601410
void cl
value of m++ 0x601430
void cl
value of m++ 0x601450
void cl
value of m++ 0x601470
void cl
value of m++ 0x601490
void cl
value of m++ 0x6014b0
void cl
value of m++ 0x6014d0
void cl
value of m++ 0x6014f0
void cl
value of m++ 0x601510
void cl
nik-pc@nik:

1 Answers1

2

The code of void cl() isn't a part of the object. The compiler knows its address statically and places it along main() and any other function inside binary.

You, basically, call a function that accepts a pointer to the object as argument, but doesn't use it. Had you try to access some fields of B inside cl(), you'd get undefined behavior.

arrowd
  • 33,231
  • 8
  • 79
  • 110
  • Not quite true. `m->cl()` gives undefined behaviour by the simple act of dereferencing `m` (which points at an invalid object, after being incremented). That dereferencing, which is what the `->` does, happens before `B::cl()` is even called. The call of `B::cl()` ALSO gives undefined behaviour, but that comes after dereferencing `m`. Undefined behaviour is not required to have a visible symptom, in either case. – Peter Mar 26 '16 at 09:22