# Pure virtual function use case question

## Recommended Posts

Hi, I'm writing a Pong clone and sort of learning C++ at the same time. In the game I have one paddle controlled by the computer and one by the user, but for now I have just one Paddle class.

class Paddle
{
public:
Paddle();
Paddle(Position p);
void setPosition(Position p);
void moveUp();
void moveDown();
void moveTowardGoal(int goal);
Position getPosition() const;

protected:
int xpos;
int ypos;
int vel;
};


Now I want the moveUp/moveDown methods to move the paddle different distances depending if it's the AI paddle or the user paddle, so I was going to create two child classes, AIPaddle and UserPaddle. However, I am not going to be using polymorphism, as I need to be able to call the moveTowardGoal method, which would only be in the AIPaddle child class. My question is, since the moveUp/moveDown functions are in both child classes (with different implementations), is it "best practice" to declare them in the base class as pure virtual even if polymorphism isn't happening? Or should I just define separate moveUp/moveDown functions in each child class? I doubt it makes any difference performance- or conceptual-wise in this simple case, but as I said I'm trying to learn the C++ way of thinking about things so I'll have a blueprint if something more complex happens in the future.

#### Share this post

##### Share on other sites

I don't like it.

If your move distance is different for different kinds of paddles I would make it a member of the class initialised in the constructor (and make it const if it is only initialised by the constructor and not changed after construction).

I would have an external class to update the position, the player paddle gets user input to move it and the AI paddle calls moveTowardGoal with a reference to the Paddle instance. You don't want to place your key input or AI logic in the Paddle class at all.

EDIT: So you probably want a boolen in the paddle as well whether it is a player paddle or not (maybe having the skill level of the AI instead of just a boolean, with skill level 0 being human controlled).

You can also use that to change the human paddle to AI control at run time (which you couldn't do with inheritance).

Edited by Paradigm Shifter

#### Share this post

##### Share on other sites

Thank you, that's a lot simpler than what I was about to do! Sometimes I can't see the forest because of the trees.

Edited by ShereModulus

#### Share this post

##### Share on other sites

it is maybe too generic at your level, but when inheritance comes to mind, before deciding to design it, there is a tool named "liskov substitution principle" (https://en.wikipedia.org/wiki/Liskov_substitution_principle) that helps.

pure virtuality in C++ is a way to design a strong contract. in practice it just says the functions must be overriden (re-implemented) in the base classes. you must already know that. Also note that it doesn't mean that a pure virtual method has no body. it can have one, just never defined on the same line that the declaration. (must use deported definition)

#### Share this post

##### Share on other sites

You can define a pure virtual function wherever you want... you still have to override it of course. It just means you can call the base class implementation if you want to.

#### Share this post

##### Share on other sites

I wouldnt use a boolean to Identify whether the paddle is an AI paddle or not as you can do this with variables in the code itself just keep two variables around one that is player controlled and one that is AI controlled.

I would replace your moveUP and moveDown functions with a single move function that takes a the inputstate as a parameter, I would remove the moveTowardsGoal as well and stick that in an AI controller. With these changes the AI controller can then get the position of it's paddle to the towardsGoal calculation and decide what it's inputstate should look like that it then feeds to the the AI paddle move function. This way your AI usage of the paddle is the same as that of a human player which is nice as that means your application flow is the same for both.

Just as a side note as soon as you add a virtual function to a class, make the destructor of that class virtual as well to avoid problems once you start inheriting from that class.

#### Share this post

##### Share on other sites

What if you want 2 human players? 2 AI players? Also you can have one paddle AI controlled and then enable a human to jump in and take control with a member variable.

Another option is to have a an abstract Controller member pointer which is the base class for HumanController, AIController which is responsible for the update.

Edited by Paradigm Shifter

#### Share this post

##### Share on other sites
The point is that you do not need that member variable and even with my solution that is easy to fix instead of passing it through the AI controller you pass it the actual input that comes from pad two problem solved. If you have a list for each of the human and AI players you move it from one list to the other. The boolean in the paddle class makes it encode state that it doesn't need to do it's job and as such shouldn't be part of that class. Edited by NightCreature83

#### Share this post

##### Share on other sites

Ugh.

Loose coupling for the win: a paddle should not point to its controller, but rather vice versa. Not all paddles need to have controllers, but all controllers need to have a paddle. Code accordingly.

Also, single responsibility is important.

This is what I would write:

class Paddle
{
public:
void Move(int velocity)
{
CurPosition += velocity;
}

int GetPosition() const
{
return CurPosition;
}

private:
int CurPosition;
};

class Controller
{
public:
virtual ~Controller() { }

virtual void MovePaddle(Paddle& p) = 0;
};

class HumanController : public Controller
{
public:
virtual void MovePaddle(Paddle& p) override
{
// Read input state
p.Move(inputvelocity);
}
};

class AIController : public Controller
{
public:
AIController(const PositionedObject& t, int maxspeed)
: TargetObject(t),
MaxSpeed(maxspeed)
{ }

virtual void MovePaddle(Paddle& p) override
{
int targetpos = TargetObject.GetPosition().GetY();
int unclampedvelocity = targetpos - p.GetPosition();
int clampedvelocity;

if(std::abs(unclampedvelocity) > MaxSpeed)
clampedvelocity = (unclampedvelocity > 0) ? MaxSpeed : -MaxSpeed;
else
clampedvelocity = unclampedvelocity;

p.Move(clampedvelocity);
}

private:
const PositionedObject& TargetObject;
const int MaxSpeed;
};

Representing paddles and [i]moving them[/i] are separate concerns. They should not be crammed into the same class (single responsibility). No variable, function, or class should have more than one reason to exist.

Extending the idea of moving a paddle around should be a matter of following the interface contract, not modifying the code of paddles as you would with the boolean flag solution (open/closed rule). In this approach, I can add an infinite number of means of moving paddles without [i]changing[/i] any code - just adding new code. This is as it should be.

In building my paddle controller, I take care to obey Liskov substitution - which has already been mentioned. In a nutshell: if I expect a Base object but I'm handed a Derived object, [i]I should never know the difference[/i]. Moreover, that Derived might actually be a Derived2 and I should not need to care.

Interface segregation is also important: never bundle logic that is unrelated. (The OP's solution runs afoul of this.) The AI paddle is the only thing that relies on knowing the ball's position, or has any notion of a "target" position, so don't pollute other code with those ideas.

Dependency inversion is also relevant here. Note that I made the AI controller talk about a positioned object, not a ball. In brief: never depend on implementations. Depend on abstract contracts and interfaces. If I want the AI paddle to follow something besides the ball, I just give it a different object! If the implementation of the ball changes, it won't break the AI, and so on.

For those following along at home: these are the SOLID design principles, and well worth learning about.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

## Sign in

Already have an account? Sign in here.

Sign In Now

• ### Forum Statistics

• Total Topics
628275
• Total Posts
2981740

• 10
• 11
• 17
• 10
• 9