This is my c++ code:
class base
{
public:
int bval;
base(){ bval=0;}
void give() { std::cout<<bval<<":"; }
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i<size; i++,arr++)
std::cout<<arr->bval;
std::cout<<"\n";
for(int i=0; i<size; i++,arr++)
arr->give();
std::cout<<"\n";
}
void test_case4()
{
base BaseArr[5];
SomeFunc(BaseArr,6);
}
I am getting following output for above code:
000003379188
0:-1079809464:134515567:134515888:0:-1079809336:
Why isn’t the second line same as the first and why I am getting a output for the 6th loop in SomeFunc when that place hasn’t been allocated, I mean there is no code for give() function to execute.
One more thing I know that sizeof operator on a object gives only the size of its data elements not the function that object contain. So if the functions are not located inside the object memory space then where are they stored?
EDIT:
I intentionally incremented the arr for 6th time just to check what happens on executing give() function that isn’t located on the 6th position.
See the comment to Cem Kalyoncu reply.
Please also answer the first part of my question.
Your array, BaseArr has 5 elements, not 6. Its upper bound is 4.
EDIT:
For why you are getting output: in C arrays doesnt have fixed limits, you can easily go out of bounds without getting any errors. Result is generally catastrophic. You will never know what will happen.
EDIT 2:
Today my mind works extra slow, now I understand why you are puzzled. Ok, even if the object pointed by arr is not valid. It is still a memory location. While calling arr->give you are actually calling a function similar to give(arr) . since arr is just a pointer to a memory location call is valid and will not raise any errors, like in c. However, some debuggers are able to notice that you run out of bounds. It is for this purpose vectors are always recommended.