Question

I have a doubt with upcasting with pointers in C++.

I'm going to write an example of my problem:

class A {}
class B : public A {}

A* pA = new A();
B* pB = new B();

pA = pB; //fails
pA = dynamic_cast<A*>(pB); //fails

I don't know what I'm missing. I think I don't understand at all the upcasting. Any help please? Thanks

UPDATED With the error:

[exec] ..\asdf\qwerty.cpp(123) : error C2681: 'B*' : invalid expression type for dynamic_cast

I have found how it works, like this:

pA* = (pA*)pB; 

But I don't understand why.

EDIT: My editor is telling me that: "a value of type B* cannot be assigned to an entity of type A*". What does this mean?

To be more exactly, pB is being returned by a function. I don't know if it has something to do: is like this:

class C { 
    B* pB;
    B* getB() { return pB; }
}

A* pA;
pA = c.getB(); //this crashes. c was declared before... it is just an example
Was it helpful?

Solution 2

You are missing semicolons ; after class definitions:

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

Also for dynamic_cast to return a meaningful result you need at least one virtual method in A. You need to have virtual destructor in a polymorphic base class for destruction to work correctly anyway:

class A {
public:
  virtual ~A() {}
};

OTHER TIPS

You are missing semicolons in your classes definition. Upcasting in C++ is totally legal and can be done in an implicit way (polymorphism). This works for me :

class A {

public:
  virtual ~A() {}
};

class B : public A {};

int     main()
{
  A* pA;
  B* pB = new B();

  pA = pB;
  delete pB;
  return (0);
}

Also, you should declare the destructor of A as virtual to avoid potential memory leaks. If you do not and try to delete the instance of B, the destructor of A will be called, but the destructor of B will not be called, leaving all the allocated resources held by B unfreed.

no reason for pA = pB; not working, it should work, what do you mean by "fails"? pointer upcast is trivial and can be used without dynamic casting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top