sara said:
Hi All,
I have multiple classes and almost all of them want to call a single
function. One way to do this is to create a single class consisting
of that function and then initialize the class whenever I want to call
the function. In this way the used class has only one member function.
Is there a more efficient way?
Thanks.
As others said, it depends on what you are trying to do.
Just for an idea:
#include <iostream>
#include <vector>
class Common{ public:
virtual ~Common(){} // look up "rule of three"
virtual void DoThing( std:
stream &out ){
out<<"Do something here."<<std::endl;
}
};
class First : public Common{ public:
void Thing( std:
stream &out){
out<<"class First: ";
DoThing( out );
}
};
class Second : public Common{ public:
void Thing( std:
stream &out){
out<<"class Second: ";
DoThing( out );
}
};
int main(){
using std::cout; // for NG post
First MyFirst;
MyFirst.Thing( cout );
Second MySecond;
MySecond.Thing( cout );
cout<<std::endl;
std::vector<Common*> Rack;
Rack.push_back( &MyFirst );
Rack.push_back( &MySecond );
for( std::size_t i(0); i < Rack.size(); ++i ){
First *pF( dynamic_cast<First*>( Rack.at(i) ) );
if( pF ){ pF->Thing( cout );}
Second *pS( dynamic_cast<Second*>( Rack.at(i) ) );
if( pS ){ pS->Thing( cout );}
} // for(i)
return 0;
} // main()
/* -output-
class First: Do something here.
class Second: Do something here.
class First: Do something here.
class Second: Do something here.
*/
If you are worried about 'efficient', measure.