Search code examples
c++pointersupcasting

Upcasting pointers


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

Solution

  • 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() {}
    };