McLovin
McLovin

Reputation: 3417

Cast derived class to base

What type of cast takes place here (in B::get())?

class A {
public:
    A() : a(0) {}
    int a;
};

class B : public A {
public:
    A* get() {
        return this; //is this C-style cast?
    }
};

int main()
{
    B b;
    cout << b.get()->a << "\n";

    system("pause");
    return 0;
}

I've seen this kind of code in a famous API. Is it better practice to do static_cast<A*>(this);?

Upvotes: 12

Views: 17814

Answers (2)

TartanLlama
TartanLlama

Reputation: 65580

This is a standard derived-to-base pointer conversion. The rules are that a pointer to D with some const/volatile qualifications can be converted to a pointer to B with the same qualifiers if B is a base class of D.

The standard conversions are implicit conversions with built-in meanings and are separate concepts to things like static_cast or C-style casts.

Generally it's best to rely on implicit conversions when you can. Explicit conversions add more code noise and may hide some maintenance mistakes.

Upvotes: 13

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

It is implicit conversion to ancestor. Implicit conversions are generally safe and they cannot do stuff static_cast cannot do. They actually even more restricted: you can do an unchecked downcast with static_cast, but not with implicit conversion.

Upvotes: 3

Related Questions