By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

upcasting pointer-to-pointer-to-class

P: n/a
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
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Judith" <ju*****@inet.co.za> wrote in message news:4d**************************@posting.google.c om...

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.
Jul 19 '05 #2

P: n/a
On 17 Nov 2003 07:48:14 -0800, ju*****@inet.co.za (Judith) wrote:
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
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.