+ 3

why output is not zero

Hello Below is sample code: https://code.sololearn.com/cUgCQw4rxsLg I thought output is zero as uninitialized array should not be used but it might give zero value. Here, structure has two element and hence a[2] is third element which should be unassigned I guess. Please help me understand output

15th Jun 2020, 2:27 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Antworten
+ 3
The reason is: virtual void f() {} The virtual method causes a function pointer address to get stored with your struct. That function pointer is the size of 2 int's. If the method wasn't virtual, there wouldn't be an address of f stored in each instance of the struct. Notice that the following will print 22 just the same. I commented out the virtual method and changed the array index from 2 to 0. #include <iostream> using namespace std; struct A { int data[2]; A(int x, int y) : data{x, y} {} //virtual void f() {} }; int main(int argc, char **argv) { A a(22, 33); int *arr = (int *) &a; cout << arr[0] << endl; cout << "Number of bytes in struct A: " << sizeof(struct A) << endl; return 0; } Note that you don't need the std:: prefix since you indicated that you're "using namespace std" above. The sizeof returns 8 in that example but 16 when f is declared as a virtual method because the function pointer is 8 bytes.
15th Jun 2020, 3:12 PM
Josh Greig
Josh Greig - avatar
+ 1
I couldn't find anything saying that c++ standardizes that the virtual function pointers are always stored before the usual data members so I don't know. That is how it works with Sololearn's tools at least. I wouldn't assume that in any non-educational programming situation. This will obviously work the same way regardless of the virtual methods: int *arr = (int *) &a.data; // the (int *) casting is optional since data is an array.
15th Jun 2020, 4:48 PM
Josh Greig
Josh Greig - avatar
0
Oh...I see... I could observe virtual... Vptr is always on top of the allocated members?
15th Jun 2020, 3:49 PM
Ketan Lalcheta
Ketan Lalcheta - avatar