## Example

The following examples will use this class hierarchy:

``````struct A { int m; };
struct B : A {};
struct C : B {};
``````

The conversion from derived class type to base class type is preferred to user-defined conversions. This applies when passing by value or by reference, as well as when converting pointer-to-derived to pointer-to-base.

``````struct Unrelated {
Unrelated(B b);
};
void f(A a);
void f(Unrelated u);
B b;
f(b); // calls f(A)
``````

A pointer conversion from derived class to base class is also better than conversion to `void*`.

``````void f(A* p);
void f(void* p);
B b;
f(&b); // calls f(A*)
``````

If there are multiple overloads within the same chain of inheritance, the most derived base class overload is preferred. This is based on a similar principle as virtual dispatch: the "most specialized" implementation is chosen. However, overload resolution always occurs at compile time and will never implicitly down-cast.

``````void f(const A& a);
void f(const B& b);
C c;
f(c); // calls f(const B&)
B b;
A& r = b;
f(r); // calls f(const A&); the f(const B&) overload is not viable
``````

For pointers to members, which are contravariant with respect to the class, a similar rule applies in the opposite direction: the least derived derived class is preferred.

``````void f(int B::*p);
void f(int C::*p);
int A::*p = &A::m;
f(p); // calls f(int B::*)
`````` PDF - Download C++ for free
{"ft_lang_label":"__label__en","ft_lang_prob":0.8700524,"math_prob":0.93682945,"size":1311,"snap":"2021-43-2021-49","text_gpt3_token_len":321,"char_repetition_ratio":0.13465953,"word_repetition_ratio":0.0,"special_character_ratio":0.2761251,"punctuation_ratio":0.18088737,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9921217,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-26T18:40:27Z\",\"WARC-Record-ID\":\"<urn:uuid:3dee3787-a7fd-4e08-a987-d9067ff33734>\",\"Content-Length\":\"73488\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:6fbdc50e-0d90-4cf7-9904-4cac6b627826>\",\"WARC-Concurrent-To\":\"<urn:uuid:c22dd533-10e4-42aa-ac06-3003ff78db85>\",\"WARC-IP-Address\":\"40.83.160.29\",\"WARC-Target-URI\":\"https://riptutorial.com/cplusplus/example/12181/overloading-within-a-class-hierarchy\",\"WARC-Payload-Digest\":\"sha1:6EWQNV5V47LL74HDLFN3WG6GJ5FE3D3B\",\"WARC-Block-Digest\":\"sha1:EJ6LAKKAW636REXC5OX4TLZISP3LZKMC\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323587915.41_warc_CC-MAIN-20211026165817-20211026195817-00303.warc.gz\"}"}