Polymorphism with double pointer

The code snippet below doesn't compile( VC++ 6 compiler). The error is: error C2664: 'myfn' : cannot convert parameter 1 from 'class D ** ' to 'class A ** '
--------------
class A {};
class D : public A {};

void myfn(A** ap) {}

void main()
{
      D d;
      D *pd=&d;
      myfn(&pd);
}
--------------
But if I change the myfn() parameter to A**, and change the call to myfn(pd), it works. Why the polymorphism doesn't seem to work with double pointer?
Ponga_PunditAsked:
Who is Participating?
 
rcarlanCommented:
The address-of operator applied to a pointer is assigned a static type (i.e. decided at compile time). There is good reason for this behaviour. Look at this code:

void CreateAInstance(A** ap)
{
    *ap = new A;
}

The above is completely legal code and it should compile without a problem. You can call this function like so:

A* ap = NULL;
CreateAInstance(&ap);
ASSERT(ap != NULL);
// do something with ap
delete ap;

Again, all legal code.

Now imagine this:

D* ap = NULL;
CreateAInstance(&ap);   // this will not compile
ASSERT(ap != NULL);
// do something with ap (e.g. call a D method or access one of its data members)
delete ap;

Should the compiler allow you to compile the code above, it would enable you to shoot yourself in the foot.

Radu
0
 
balderCommented:
I guess you will find the explanation in the C++ standard, polymorphism works for pointers and references to class objects.
(Looking up the standard for you will cost you more points)

I can't understand when this should be any problem, as you always can dereference a pointer to pointer
D** p;
myfn( *p );
0
 
Ponga_PunditAuthor Commented:
Sorry friemds, there was a little typo in my question. Please read the second last line as:

>> But if I change the myfn() parameter to A* ap, and change the call to myfn(pd), it works.
But still Radu's answer is fully acceptable.
0
 
beryl666Commented:
>>But if I change the myfn() parameter to A**, and change the call to myfn(pd), it works. Why the polymorphism doesn't >>seem to work with double pointer?

did you mean myfn() parameter to A*, myfn(pd) ?
you put one more '*' there am i right?
0
 
beryl666Commented:
i was late abit. cheers.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.