class) at runtime. I'm sure this technique has been named as some kind
of pattern/idiom, but I'm not sure what exactly.
It is dynamic polymorphism. Concerning the pattern, IMO it is kin to the
Envelope/Letter pattern.
Note that it does not achieve dynamic typing (hence dynamic inheritance)
unless you implement a dispatching system. Base must have a common
interface.
even i read about this to put a wrapper function and and adding a base
pointer..
if some one could help me with a small code snippet to get hold of it..
Retaking your example
struct base_interface
{
virtual void gettype()const=0;
virtual void set_val(int val)=0;
virtual int get_val()const=0;
};
class Base1: public base_interface
{
public:
Base1(int a):val1(a){
cout<<"Constructing BASE1"<<endl;
}
virtual void gettype()const {
cout<<"BASE1";
}
virtual void set_val(int val){
val1=val;
}
virtual int get_val()const{
return val1;
}
protected: int val1;
};
class Base2: public base_interface
{
//same as Base1 with val2
};
class Derived: base_interface
{
public: int val2;
Derived(int b,base_interface* b):val2(b),dynbase(b)
{ //base not null - could use default base
assert(b);
}
//set base
base_interface* base(base_interface* b)
{ assert(b);
base_interface* const tmp=dynbase;
dynbase=b;
return tmp;
}
virtual void gettype()const {
cout<<"Derived inheriting from ";
dynbase->gettype();
}
//delegating to base
void set_val(int val)
{ assert(dynbase);
dynbase->set_val(val);
}
int get_val()const
{ assert(dynbase);
return dynbase->get_val();
}
};
void display(base_interface& d)
{
cout<<"Type is"<<d->gettype()<<endl;
//...
}
int main()
{
Base1 b1(2);
display(b1);
Base2 b2(4);
display(b2);
Derived obj(1,&b1);
display(obj);
obj.base(&b2);
display(obj);
}
I have not compiled the code but it should get you started
Thnx for your effort... it really helped... and googling about