How to access the function which is defined in derived class and not in base class in polymorphism?
class base {
public:
virtual void display ()
{
cout << "base" << endl;
}
};
class derived : public base {
public:
void display (){
cout << "Derived" << endl;
}
void goo (){
cout << " new function in derived" << endl;
}
};
base * global_function ( base *ptr)
{
/**** how to invoke the derived class goo function ---Here *****/
}
int main ()
{
derived obj;
global_function ( &obj );
}
Can anyone help me how to invoke the derived class function, which is not specified in the base class?
You can downcast the base pointer
Look at Here , this contain a very good explanation of what to do
Taked from the link:
Child *p = dynamic_cast<Child *>(pParent);
Like this:
Derived *d = dynamic_cast<Derived*>(ptr);
if (d) d->goo();
dynamic_cast<Derived*>
will produce a valid Derived*
pointer if ptr
indeed points to Derived
; otherwise, NULL
pointer would be produced (note the if
that "guards" the invocation of goo()
).
In general, it is not a good idea to put dynamic_cast
to excessive use: if you need to do it a lot, it points to a potential shortcoming in the design of your class hierarchy.
You can access the method but you have to hope that base *ptr
is actually a derived*
type (which, in your case, it is).
Then you can use a dynamic_cast
to convert the pointer to the correct type:
derived* my_ptr = dynamic_cast<derived*>(ptr)
and call the method using my_ptr->goo()
. If my_ptr
evaluates to nullptr
then ptr
was not of the correct type. You'll need to test this else before calling goo
else you could invoke undefined behaviour .
But , this is an anti-pattern that circumvents polymorphism. It's far better to set up your class structure so you can avoid this cast.
The solution ( dirty and not recommended ) was the following
base* global_function ( base *ptr ) {
std::dynamic_cast<Derived>(*ptr).goo();
}
Although this might work in this specific case, just don't assume a base type pointer to contain information about foo, rather do template specialization and maintain typesafety!
template <typename T>
T* global_function(const T* ptr) {
// do nothing in this case.
}
// Specialization
template<>
base* global_function<base>(const base* ptr) {
// invoke base methods
}
template<>
Derived* global_function<Derived>(const Derived* ptr) {
ptr->goo();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.