Question

I am type casting a class to use storage set by another class. I want to invoke the constructor of the first class when type casting is performed. Is there any way to achieve this?

Consider the following code:

class A{
      int x;
public:
      A() {x = 0;}
};

class B{
      double x;
public:
      B() {x =0.0f;}
};

B * bObj = new();
A * aObj = reinterpret_cast < A * > ( bObj );     //Just for the sake of explaining

Now aObj references to the memory allocated to bObj & uses it & stores its contents there. I am trying to get the constructor of A class called when the typecasting is performed or after. Please help.

I want to use aObj and the constructor for A to be called. which doesn't happen. aObj is, no doubt ,getting memory allocated however, the constructor call doesn't happen. And it has garbage values filled in it.

Was it helpful?

Solution 2

I am learning C++ and trying to store objects in a universal buffer. (bObj acting as buffer in above snippet). aObj does have memory access but constructor call doesn't happen which Is what i m trying to achieve.

It sounds like you need to read up on placement new. See What uses are there for "placement new"? and What is "placement new" and why would I use it? for some background and examples of use.

Bear in mind that using placement new correctly requires care. It is very easy to get it wrong and end up with undefined behaviour.

In particular, you'll need to rethink how you allocate the buffer.

OTHER TIPS

Constructing an A object in the storage of a B object is generally Undefined Behavior.

You can do it (with a placement new expression) when type B is an array of char, not a class with a constructor, but it's extremely rarely needed, only for experts, and it requires manual invocation of the A object's destructor.

If you are trying to just save memory then you can

  • Ignore the memory usage.
    With today's computers that's generally the best solution.

  • Use derived classes and virtual member functions.

  • In the worst case, use a tagged union.
    "Tagged" means that there is a type identification value, a type "tag".

If you are trying to save execution time for PIMPL idiom,

  • Measure. Probably avoiding a dynamic allocation and indirection isn't really so critical.

If something else, please state what.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top