/*
PROGRAM OUTPUT
Testing without vtable...
Size of object is 4
0
1
2
3
4
5
6
7
8
9
Testing with vtable...
Size of object is 8
0
1
2
3
4
5
6
7
8
9
*/
#include <stdlib.h>
#include <iostream>
#define ARRAY_SIZE 10
using namespace std;
class VRoot {
public:
virtual void PrintValue () = 0;
};
class VRootImplemented : public VRoot {
private:
int value;
public:
VRootImplemented (int value) {
this->value=value;
}
void PrintValue () {
cout << value << "\n";
}
};
class NoVRoot {
private:
int value;
public:
NoVRoot (int value) {
this->value=value;
}
void PrintValue () {
cout << value << "\n";
}
};
void main () {
// TEST 1
cout << "Testing without vtable...\n\nSize of object is " << sizeof(NoVRoot) << "\n";
// Allocate array
NoVRoot * p_no_v=(NoVRoot *)malloc(sizeof(NoVRoot)*ARRAY_SIZE);
// Theoretically check malloc success here
// Fill array
for (int i=0;i<ARRAY_SIZE;++i) new (p_no_v+i) NoVRoot (i);
// Call PrintValue() on each item
for (int i=0;i<ARRAY_SIZE;++i) p_no_v[i].PrintValue();
// Theoretically clean up here
// TEST 2
cout << "\nTesting with vtable...\n\nSize of object is " << sizeof(VRootImplemented) << "\n";
// Allocate array
VRootImplemented * p_v=(VRootImplemented *)malloc(sizeof(VRootImplemented)*ARRAY_SIZE);
// Fill array
for (int i=0;i<ARRAY_SIZE;++i) new (p_v+i) VRootImplemented (i);
// Call PrintValue() on each item
for (int i=0;i<ARRAY_SIZE;++i) {
VRoot * test=&(p_v[i]);
test->PrintValue();
}
// Theoretically clean up here
}