drum
drum

Reputation: 5651

Cast object to base or derived class?

Is there any difference between:

cBase* object = new cDerived();

and

cDerived* object = new cDerived();

If so, in which cases do I choose one over the other?

Upvotes: 0

Views: 81

Answers (2)

Miles Budnek
Miles Budnek

Reputation: 30569

The static type of object differs in your two examples. Let's take an example:

struct A {};

struct B : A
{
    void method() {}
};

int main() {
    A* a = new B;
    B* b = new B;
    a->method(); // compile error, A has no member named method.
    b->method(); // fine. b's static type is B*, and B has a member named method
}

It doesn't matter that a actually points to a B object; its static type is A* and A has no member named method.

Upvotes: 2

ruakh
ruakh

Reputation: 183321

The difference is that they declare object as having different types, which can have lots of consequences. For example:

  • If cDerived declares any new members (beyond what it inherits from cBase), then only the version with cDerived* object makes those available (unless you explicitly downcast back to cDerived*).
  • If cBase declares any non-virtual member functions that cDerived overrides, then which one gets called depends on the type of the pointer that you use to call it.
  • If a function expects to take a cDerived*, then you can't pass it a cBase* (unless you explicitly downcast back to cDerived*).

Upvotes: 4

Related Questions