avoid cast to derived




There is example below and answer on it

Your code has a poor design. If the userUser class can only work with
userBase objects, then define it as such. If it can work with all Base
objects, then it shouldn't need to dynamic_cast the Base object it has.

Can anybody say the way to avoid cast to derived in the case?

Example:
// *** library module

#define adjust_list
#define adjust_list1
#define adjust_list2
#define adjust_list3

//object
struct Base{ virtual void method()=0; };

//Most parts of user code
struct User
{
virtual void user1(Base& obj){ obj.method(); }
virtual void user2(Base& obj){ obj.method(); }
};

struct Creator
{
virtual Base* create_base()=0;
virtual User* create_user()=0;
};


// *** user module
struct userBase: public Base
{
void adjust(adjust_list){}
void method();
};


struct userUser: public User
{
//to get extended interface of derived via pointer to its base class
void user2(Base& obj)
{
userBase *const tmp=dynamic_cast<userBase*>(&obj);
if(!tmp){ obj.method(); return; }

tmp->adjust(adjust_list1);
obj.method();

tmp->adjust(adjust_list2);
obj.method();
}
};


struct userCreator: public Creator
{
Base* create_base(){ return new userBase;}
User* create_user(){ return new userUser;}
};


// *** another user module

extern Creator& extCreator();

//Most parts of user code
int main()
{
Base &base= *extCreator().create_base();
User &user= *extCreator().create_user();
// ...
user.user1(base);
// ...
{
userBase tmp ;
tmp.adjust(adjust_list3);
user.user1(tmp);
}

// ...
user.user2(base);
}

.



Relevant Pages

  • Maximizing speed of a switch block
    ... We have a critical loop which looks like this: ... virtual void doIt; ... struct allMyVars ... void action_1(X*, allMyVars* v) ...
    (microsoft.public.vc.language)
  • Re: Pattern Protestations.
    ... oops make the pointer derferencing look prettier. ... struct D: X { ... virtual void f ...
    (comp.object)
  • Re: Call to a virtual method crashes
    ... It doesn't matter. ... virtual void f; ... struct Y1: X ... Microsoft MVP - Visual C++ ...
    (microsoft.public.vc.mfc)
  • Re: Threads on class,
    ... I have to admit that I was wrong - the ... DWORD ThreadId; ... virtual void f; ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: Threads on class,
    ... I have to admit that I was wrong - the ... DWORD ThreadId; ... virtual void f; ...
    (microsoft.public.vc.language)