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);
?
A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB , and ClassB is derived from ClassA , ClassC inherits the members declared in ClassB and ClassA .
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
Downcasting is not allowed without an explicit type cast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.
The Downcasting is an opposite process to the upcasting, which converts the base class's pointer or reference to the derived class's pointer or reference. It manually cast the base class's object to the derived class's object, so we must specify the explicit typecast.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With