First question, hope i managed to phrase it right.
While checking to see if i can "force" a buffer to behave as a class (with inheritance and vptr) , i tried the following code:
I defined the following classes:
class a
{
public:
char strBuff[50];
virtual void boo() = 0;
};
class b : public a
{
public:
virtual void boo()
{
printf("%s\n", strBuff);
}
};
And used them like this:
int main()
{
char buffer_allo[100] = "123456789abcdefghijklmnopqrstuvwxyz123456789abcdefghijklmnopqrstuvwxyz";
b* obj_Ptr = (b*)(buffer_allo);
// Placement new
new (obj_Ptr) b();
// Calling virtual function
obj_Ptr->boo();
return 0;
}
The output of the program is empty, as in a \0
buffer, and i couldn't exactly figure out why.
I thought it was some thing of a default-initialization\ value-initialization problem, and indeed changing the placement new from new (obj_Ptr) b();
to
new (obj_Ptr) b;
didn't give a blank output, but a buffer where just the first 8 characters were overwritten (Probably by the vptr),
But then, i tried adding a constructor to either class, and discovered that adding an empty constructor to class b, will also prevent the buffer from being initialized with \0
, but adding a constructor to class a seems to have no effect.
Why is this happening? is it really an initialization issue? and if so, why does adding an empty constructor solve it? or is it a compiler\c++ standard issue?