#include<iostream>
using namespace std;
class Abs
{
public:
virtual void hi()=0;
};
class B:public Abs
{
public:
void hi() {cout<<"B Hi"<<endl;}
void bye() {cout<<"B Bye"<<endl;}
};
class C:public Abs
{
public:
void hi() {cout<<"C Hi"<<endl;}
void sayonara() {cout<<"C Sayonara"<<endl;}
};
int main()
{
Abs *bb=new B;
bb->bye();
Abs *cc=new C;
cc->sayonara();
}//main
The compiler says
test2.cpp: In function ‘int main()’:
test2.cpp:26: error: ‘class Abs’ has no member named ‘bye’
test2.cpp:28: error: ‘class Abs’ has no member named ‘sayonara’
Because of this problem, I'll have to add functions to the Abs class each time I create a new derived class which inherits from it (Upcasting is compulsory for me to do. The program I'm planning requires it to be so). I don't want to touch the base class once it's created. Doesn't this problem violate the principle that once you make a base class, you won't have to modify it ever. Any way to resolve this problem? p.s: I've seen the factory design pattern and the prototype design patterns, but both of them can't seem to be able to solve it.
Dynamic casting is a sensible option. If you're religious about dynamic casts, you can use the visitor design pattern:
and then you use
Do this only when you really need it.
This way modifications in the base class are no longer needed :)
This is defeating the purpose of inheritance and abstract interfaces.
bye
andsayonara
both do the same thing (saying goodbye), only in different languages. This means you should have an abstractsay_goodbye
method that gets overridden for subclasses. I suppose this is a simplified example, so maybe you could describe your actual scenario so we can provide more specific help.Edit If you want to create a copy of the derived class through an abstract interface, check out this question. If you want to explicitly access the different attributes of your subclasses, you should be asking your self if subclassing es even appropriate here, since your classes don't seem to have much in common.
If upcasting is compulsory and you need to call methods defined in the subclasses then You're Doing It Wrong.
However, at a given point in time, you either know that an object is a specific subclass, in which case you can dynamically cast to that type, or you don't and can't be sure you can call the function.
Assuming this is related to your other question, I've tried to explain a way to implement that particular problem in a different manner there.
Well, i'm not sure to understand exactly what you want (and why you want it that way) but:
Will work.
You just have to be sure that
bb
is really aB*
before youstatic_cast
.You may also use
dynamic_cast
which will return a null pointer ifbb
is not of the correct type.