Home > Back-end >  Copying an array of Object Pointers
Copying an array of Object Pointers

Time:10-04

What would be the correct way to copy an array of pointers pointing to a certain object into another object through the constructor?

Assuming that:


// ClassA.h

class ClassA {
  ClassB** m_classBs{};
public:
  ClassA(const ClassB* classBs[], size_t cnt);
}


ClassA::ClassA(const ClassB* classBs[], size_t cnt) {
  m_classBs = new ClassB*[cnt]
  for (size_t i = 0; i < cnt; i  ) {
    m_classBs[i] = &classBs[i];
    // I have tried here using *m_classBs[i] = &classBs[I];
    // and a lot of variations but neither seems to work for me 
    // at the moment. I am trying to copy the array of pointers
    // from classBs[] (parameter in the constructor) to m_classBs
  }
}

CodePudding user response:

You have to use use the correct type:

class ClassA {
  const ClassB** m_classBs;
public:
  ClassA(const ClassB* classBs[], size_t cnt);
};


ClassA::ClassA(const ClassB* classBs[], size_t cnt) : m_classBs(new const ClassB*[cnt]) {
  for (size_t i = 0; i < cnt; i  ) {
    m_classBs[i] = classBs[i];
  }
}
  •  Tags:  
  • c
  • Related