Bendegúz Nagy Bendegúz Nagy - 1 year ago 80
C++ Question

C++ object creation without constructor call

In c++, creating an object without calling a constructor like this. Does this count as defined behavior? (Disregard the unfreed heap memory)

class Foo {
int *ptr;
int a, b;

Foo() { ptr = new int{}; }
~Foo() { delete ptr; }
void set(int a_, int b_) {a = a_; b = b_;}
void print() { std::cout << *ptr << a << b; }

int main() {
char *array[sizeof(Foo)]; // note the pointer
*((int**)array) = new int{3};
((Foo*)array)->set(1, 2);
((Foo*)array)->print(); // 312

Answer Source

You are building a memory block that can hold the data for the object, but that is not an object.

An object consist of potentially a lot more than that slice of memory, and what exactly more is up to the compiler. It could be nothing more, but it could be a lot of other things.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download