Home > Blockchain >  Initialize a heap object using constructed non-heap object
Initialize a heap object using constructed non-heap object

Time:12-15

So, I have class A, and I have created object A obj1 , but now I want to create a heap object using new operator A *obj2 = new A(int x) , but using the data from obj1 without having access to members of obj1.

Can I initialize members of obj2 using obj1 without having access to obj1 members (public access or through get functions)?

(I'm sorry if my question is...incomprehensible)

CodePudding user response:

Can I initialize members of obj2 using obj1

In your example, obj2 has no members because it's a pointer. I suppose that you want the dynamic object to be a copy instead.

If the type is copy-constructible and you have access to it, then you can simply use copy initialisation. Here is an example:

auto ptr = std::make_unique<A>(obj1);

P.S.

  • Don't use bare owning pointers.
  • Avoid unnecessary dynamic allocation.

CodePudding user response:

Sure. The copy constructor will need access, but it can access private member variables.

class A {
  private:
    int x;
};

void foo(A stack_allocated) {
  A *heap_allocated = new A(stack_allocated);
}
  •  Tags:  
  • c
  • Related