Hello,
I have a question regarding downcasting of base class pointers. I am providing a sample class design which is similar to my program.
class A
{
protected:
double num1;
public:
virtual void fn1() = 0;
};
class B:public class A
{
protected:
double num2;
public:
virtual void fn1(); // performs some operation on num1
void fn2(); // performs some operation on num2
};
class C:public class A
{
protected:
double num3;
public:
virtual void fn1(); // performs some operation on num1 and num3
};
int main()
{
A *a1, *a2;
a1 = new B;
a2 = new C;
// downcasting here
B *b = dynamic_cast<B *>(a1);
b->fn2();
a2->fn1();
}
The function fn2() and num2 are specific to class B and it wouldn't make sense to have them in the base class. The question is there any change that I can do in the class design to prevent this downcasting the base class pointer? In some forums and book, it is said that downcasting indicates poor design. I feel in this kind of situation downcasting can't be avoided. Am I right in assuming this?
Thanks in advance,