Convert Derived** to Base**

D

danil52

class A {};
class B : public A{};

void f (A* a[]) {}

int main() {
B* b[2];
b[0] = new B();
b[1] = new B();

f(b);
return 0;
}

Compiler says it cannot convert B** into A**. What am I doing wrong?
Thanks.
 
D

danil52

class A {};
class B : public A{};
void f (A* a[]) {}
int main() {
  B* b[2];
  b[0] = new B();
  b[1] = new B();
  f(b);
  return 0;
}
Compiler says it cannot convert B** into A**. What am I doing wrong?

Nothing.  There is no conversion between those.  Classes are related.
You are hence allowed to convert between pointers to those classes.  But
pointers to those classes are not related, so conversion between
pointers to pointer to those classes does not exist.

What are you trying to accomplish?  What does your _real_ 'f' do with
the pointers?

V

I want to perform an action on each element of array, polymorphically
(e.g. call virtual function, that was declared in class A). Should I
just use vector<A*> instead?
 
D

danil52

Nevermind, that was a stupid mistake on my part. If I want to use
array polymorphically, I should declare it that way too.

A* b[2];
b[0] = new B();
b[1] = new B();

f(b);
 
D

danil52

class A {};
class B : public A{};
void f (A* a[]) {}
int main() {
  B* b[2];
  b[0] = new B();
  b[1] = new B();
  f(b);
  return 0;
}
Compiler says it cannot convert B** into A**. What am I doing wrong?
Thanks.

Consider this example (which will fail to compile, but is illustrative).
Ignore the memory leaks, they're not relevant to the point being made.

#include <iostream>

struct B {};

struct D1 : public B
{
        void f() const
        {
                std::cout << "D1::f()" << std::endl;
        }

};

struct D2 : public B {};

void f(B *arr[])
{
        arr[0] = new D2;

}

int main()
{
        D1 *arr[2];
        arr[0] = new D1;
        arr[1] = new D1;
        f(arr);
        arr[0]->f(); // BOOM
        return 0;

}

If the conversion from D1** to B** were allowed, f() could change arr[0]
to point to a D2 (since a D2 is a B, a D2* can be converted to a B*).
Back in main(), arr[0] is expected to point to a D1. The call
arr[0]->f() would thus be valid. The only problem is...arr[0] no longer
points to a D1! Result: danil52 0, Computer 1.

So it's really just as well that this conversion isn't allowed. The same
thing goes for containers in general. A container of D1s is *not* a
container of Bs, because you can add a D2 to a container of Bs, and you
can't add a D2 to a container of D1s.

Regards,
Stu

Thanks Stu. That was a great example!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top