Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,


C#
#include <iostream>

using namespace std;


class Base
{

public:
Base(){}
~Base(){}

virtual void func1()
{
cout<<"Base_ONE"<<endl;
}

};


class Derived : public Base
{
public:
Derived(){}
~Derived(){}

void func1()
{
cout<<"Base _TWO"<<endl;
}

};


int main()
{
/* Base a;
Base *ba;

Derived b;
Derived *db;

//ba=&b;
ba=dynamic_cast<Base*>(&b);
if(ba)
cout<<"Conversion Success"<<endl;
else
cout<<"Conversion Fail"<<endl;

ba->func1();
*/

Base* b = new Derived;
b->func1();


Base* bb;
Derived d;
bb=&d;
bb->func1();

Base* bbb;
Derived ddd;
bbb=dynamic_cast<Base*>(&ddd);

bbb->func1();

return 0;
}





In above example , i am able to access the derived class member function in three ways.

1)using base class pointer object , i am able to access the derived class function.
2)assigning the derived class object address to base class pointer object.
3)using dynamic_cast.

Here my question is , which method should i go for to access the derived class function using base class pointer and why?



Regards,
Ranjith
Posted
Updated 4-Jan-13 2:08am
v5
Comments
Sergey Alexandrovich Kryukov 4-Jan-13 7:51am    
Dynamic cast for polymorphism is almost like... cutting out a head to treat headache.
—SA

1 solution

It depends on your needs.
Note you don't need the static_cast in your third case, namely:
C++
Base* bbb;
Derived ddd;
bbb=&ddd;
ddd->func1();


works fine.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900