upcasting pointer-to-pointer-to-class

J

Judith

Hi there everyone

I've got:

class A
{ ... };

class B : public A
{ ... }

void foo(A** a)
{ ... }

int main(...)
{
B* b = new B();
foo(&b);
}

GCC complains with "passing 'B**' as argument 1 of 'foo(A**)'"

Upcasting through one level of reference is most common, why is this different?

Thanks for any insight,

Judith
 
R

Ron Natalie

Judith said:
GCC complains with "passing 'B**' as argument 1 of 'foo(A**)'"

Upcasting through one level of reference is most common, why is this different?
Didn't we just answer this (look around on the group).

class Base { };
class Derived : public Base { };

Base b, *bp, **bpp;
Derived d, *dp, **dpp;

dp = &d;
bp = dp; // fine, we know how to convert from Derived* to Base* and can do so in this operation.
bpp = &dpp; // we convert from Derived** to Base** ok, but how does the value *dpp get converted
// to *bpp?

It's not a safe conversion because the compiler at the time *bpp is used doesn't know
what conversion might be needed to apply to the value to make it really a Base* value.
 
T

tom_usenet

Hi there everyone

I've got:

class A
{ ... };

class B : public A
{ ... }

void foo(A** a)
{ ... }

int main(...)
{
B* b = new B();
foo(&b);
}

GCC complains with "passing 'B**' as argument 1 of 'foo(A**)'"

Upcasting through one level of reference is most common, why is this different?

Here's why it doesn't work. Imagine that it did work, and then
consider this:

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

void foo(A** a)
{
*a = new A;
}

int main()
{
B* bPtr;
foo(&bPtr);
//Oh no, bPtr now points at an A, but no compiler error!
}

The workaround is to change your main method to:

B* b = new B();
A* a = b;
foo(&a);
//a might be pointing to an A rather than a B...

Tom
 

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,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top