Re: OOPs way to do this in C++?
Jim Langston wrote:
Any suggestions on how to improve the design?
The correct answer, as aiouua said, is to use the decorator pattern.
Anyway, I wanted to point out that even with your design you don't need
any friend function. Consider this:
#include <iostream>
#include <string>
#include <functional>
class Base
{
private:
void Walk();
void Fly();
void Swim();
void Float();
public:
Base( int X, const std::string Movement ): Move_( NULL ), X(X)
{
if ( Movement == "Flies" )
Move_ = std::mem_fun_ref(&Base::Fly);
else if ( Movement == "Walks" )
Move_ = std::mem_fun_ref(&Base::Walk);
else if ( Movement == "Swims" )
Move_ = std::mem_fun_ref(&Base::Swim);
else if ( Movement == "Floats" )
Move_ = std::mem_fun_ref(&Base::Float);
else
Move_ = std::mem_fun_ref(&Base::Walk);
}
void Move() { Move_(*this); }
private:
std::mem_fun_ref_t<void, Base> Move_;
int X;
};
void Base::Walk()
{
X += 5;
std::cout << "Walked to " << X << "\n";
}
void Base::Fly()
{
X += 7;
std::cout << "Flew to " << X << "\n";
}
void Base::Swim()
{
X += 3;
std::cout << "Swam to " << X << "\n";
}
void Base::Float()
{
X += 2;
std::cout << "Floated to " << X << "\n";
}
int main()
{
Base MyBase( 10, "Flies" );
MyBase.Move();
std::string wait;
std::getline( std::cin, wait );
return 0;
}
As already said, it;s better to decorate, having a Base with
virtual Move() = 0;
and each derived class implement a different Move().
Regards,
Zeppe