Reputation: 13
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?
Upvotes: 1
Views: 75
Reputation: 1360
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();
}
Upvotes: 0
Reputation: 234695
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.
Upvotes: 1
Reputation: 726569
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.
Upvotes: 2
Reputation: 23515
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);
Upvotes: 2