Search code examples
c++pointersconstructorallocation

What does a not defined constructor do exactly


I got a program where i got a class "agent" and there are a number of sub-classes that implement the functions of agent (and have extra fields (int float etc). The idea is that i can iterate through a vector of agent pointers and call the functions regardless of the underlying class.

So far so good.

I got more experience with c, so i allocated memory with malloc (i know this isn't the right way but hold on for a sec).
Like this:

bee* b = (bee*) std::malloc(sizeof(bee));

Now i thought i got memory allocated and a pointer pointing on the memory telling me (or more precisely c++) where what is and what functions i can call. And in fact i can do all of that. But when i push_back() that pointer in my vector of agents and then try to call the functions my program just crashes without any error messages. (Also debugging isn't helpful or i am to bad at it).

I can fix that problem by either:

bee* b = (bee*) std::malloc(sizeof(bee));
b = new (b) bee();  // calling the constructor manually

or

bee* b = new bee;   // using the c++ way of allocating which automatically calls the constructor

That begs 2 Questions:

  • What does the default constructor do
  • And why does it solve the error.

Thank you for your help.

Edit:

I got told that the constructor "initializes the object". I seem to have no idea what that means. In my understanding i have a piece of memory and "i know what is stored there" and its "overwrite protected" or "allocated". What is the difference between that state and the initialized one. What more information is there? Where is an initialization stored. I don't get it. Don't i know from the pointer that one class is the subclass of another class ?


Solution

  • malloc() allocates memory but does not create objects in C++. That's why you cannot simply call malloc() and pretend there's an object in that memory. More specifically, malloc() does not call any constructor, and many C++ types cannot be used without a constructor being called.

    It's like building a chicken coop and expecting to get eggs: you've missed the most important step.