Question

Below is my code

Class A
{
  A::A(int num) { }
  int num;
};

class B : public A
{
  B::B(int num):A(num) { }
};

Class D;
Class C
{
  void getNum(A**& somenum) {}
  D *dObj;
};

void C::getNum(A**& somenum)
{
  dObj->getNumber(static_cast<B**>(somenum)); // Error here.
}

Class D
{
  void getNumber(B**& number) 
  { 
      B someValue[5];
      // all the objects in the array are properly created and properly Initalized (skipped that part)

      number[0] = someValue[0]; 
      number[1] = someValue[1];
      //...
   }
};

I'm getting compilation error while doing the static_cast. I am trying to assign the values in "someValue" array to "A**& somenum". Can you please help how to do it.

Thank you very much in advance.

Était-ce utile?

La solution

Your compiler is doing the right thing here. In short, you can't do that. You can convert between a base class pointer and a derived class pointer, provided they point to the same object. But an array-of-Base and array-of Derived are not the same thing.

The good news is what you want to do is easier than you think. A derived class pointer already implicitly converts to a Base class pointer without casting. Assuming you know the sizes of your two arrays, and the sizes are the same, it's a simple loop:

// Given:
A** someNumbers;
B** someValues;

for (int i = 0; i < size; ++i) {
    *someNumbers[i] = *someValues[i];
}

Also, this sort of problem is why we have standard containers like vector. Some really smart people have already solved this pointer madness for you. I highly recommend taking advantage of it. It'll make your C++ experience a ton better.

Autres conseils

void C::getNum(A**& somenum)
{
  dObj->getNumber(static_cast<B**>(somenum)); // Error here.
}

static_cast is used to perform conversions between pointers to related classes, or to perform any other non-pointer conversion that could also be performed implicitly. which is not the case in your above example. so that's why static_cast can't be used here.

Because C++ supports multiple inheritance (and other features), an A * is convertible to a B * but not necessarily identical to a B *. Converting between the pointer types could move the pointer value by a some number of bytes.

As a result, it's impossible to convert an A ** to a B ** or vice versa. The base-to-derived conversion would need to happen after retrieving the value from the outer pointer.

Multiple indirection is usually a bad idea. It's hard to know what data structure might help, but a review of the standard library containers might be insightful. Anyway, thanks for condensing down this nice self-contained example!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top