12

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);?

McLovin
  • 3,295
  • 7
  • 32
  • 67

2 Answers2

13

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.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • Strictly, "can be converted to a pointer to `B` with the same *or more* qualifiers" – Martin Bonner supports Monica Dec 14 '15 at 14:09
  • 3
    I suggest specifically answering his question: "No, it is not better practise to use `static_cast` - in fact, it is worse practise. Always avoid casts if you don't need them." – Martin Bonner supports Monica Dec 14 '15 at 14:11
  • @MartinBonner Disagree! Implicit casts are the source of all sorts of wacky bugs. Sometimes I wish C++ didn't even have them at all... Nothing wrong with being explicit. – Barry Dec 14 '15 at 14:34
  • @Barry are you referring to standard conversions or user-defined conversion operators or both? – TartanLlama Dec 14 '15 at 14:35
  • @Barry can you give an example of a bug caused by implicit cast? – McLovin Dec 14 '15 at 14:36
  • I'd prefer the phrasing "implicit conversions". The trouble is that they are still there, but static_cast gives you the opportunity to be explicitly wrong. – Martin Bonner supports Monica Dec 14 '15 at 14:36
  • @Barry Also, shouldn't the compile error out if you are about to make an implicit mistake? – McLovin Dec 14 '15 at 14:38
  • Some kinds of implicit conversions are indeed error-prone, one famous example being the signed-to-unsigned promotion on comparisons. Many tools warn on such conversions, and a cast to alert the reader is a good idea. For a derived-to-base conversion i agree that the cast does more harm than good. If a coding convention requieres a cast here, `static_cast` is the way to go, but i would argue that the convention is broken. – Michael Karcher Dec 14 '15 at 15:57
3

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.

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48