[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 514
  • Last Modified:

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?
0
Ponga_Pundit
Asked:
Ponga_Pundit
1 Solution
 
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
 
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
 
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now