when we explicit typecaste the base to derived, it is working,
as understand the base object passed has no details of the derived class, then how can the derived class function gets called after typecasting base pointer.
#include<iostream>
usingnamespace std;
class a
{
int a0;
int a1;
public:
void af() { cout<<"In a::af\n"; }
};
class b: public a
{
int a2[100];
int a3;
int a4;
public:
void bf() { cout<<a2[50]<<"In b::bf\n"; }
};
class c: public b
{
public:
void cf() { cout<<"In c::cf\n"; }
};
void fun(a*p)
{
((c*)p)->cf();
}
main()
{
a t;
fun(&t);
}
Nobody has any information on anything. The thing on the left of -> on line 33 is a pointer to c, because it has been forcefully cast to c*, so a member function of c will be called. If you want the function called to depend on the actual type, consider virtual functions. If you want a conversion which fails if it is impossible, consider dynamic_cast.
It worked because cf() doesn't access any member fields of class c. C++ compilers put the methods in a section in memory and this section is shared by all instances of the corresponding class. When a method is called, the 'this' pointer is defined and then the method is called with this 'this' pointer.
Conclusion: Yes, it is the equivalent of reinterpret_cast, and it works only because it doesn't access data members that are specific to class c. If you were to add a member field to class c and access it in cf(), then you would see how this blows up.
This is not undefined. C++ standard section 5.4 part 5 wrote:
The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion. The same semantic restrictions and
behaviors apply. If a conversion can be interpreted in more than one of the ways listed above, the interpretation
that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.<...>
so we can casting to another type as long as they have "relationship" but we can access their specific member? is there's another type have this kind of behavior?