When would I need a Virtual Function? - function

I understand that a Virtual Function is a function that can be redefined in classes that inherit that function.
Yet, I do not understand why I would need a Virtual Function. Can someone explain me or show me cases where I would need Virtual Functions?
Thanks!

There is nice explanation with good example
https://en.wikipedia.org/wiki/Virtual_function

Any function can be redefined in a class' inheritors. The key to virtual functions is that they are supposed to be overriden.
Suppose you have a polygon class (in C++):
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return 0; }
};
Now it doesn't make sense to define the Polygon.area function inside the polygon class, because at this level you don't know what the polygon is. The existence of the virtual function enforces all inheritors to implement their own version of the function.

Related

'Gdiplus::Graphics' : no appropriate default constructor available

Not sure what I am doing wrong.. I have a very muddy idea of how Constructors should be formatted or structured, so any insights would help!
Renderer.h
#pragma once
#include <afxwin.h>
#include <winapifamily.h>
#include <wtypes.h>
#include <gdiplus.h>
class Renderer
{
public:
Renderer();
~Renderer();
void Clear(Gdiplus::Color clearColor);
virtual void Free() = 0;
virtual void LoadFace(int index, char* path) = 0;
void InitFromHDC(HDC dc);
void Shutdown();
// Drawing surface
Gdiplus::Graphics _graphics;
protected:
private:
bool _gdiplusActive;
};
Renderer.cpp
Renderer::Renderer()
: _gdiplusActive(false)
{ // <-error here
}
Renderer::~Renderer() {}
...
I tried many variation of adding variables... but honestly, the error may be obvious who understands what a default constructor is. I dunno.
A default constructor is a construtor that takes no parameters.
You can't create a Gdiplus::Graphics out of thin air, you need to give it something to draw on: a bitmap, a window or a device context.
Here is the list of constructors available:
https://learn.microsoft.com/en-us/windows/win32/api/gdiplusgraphics/nf-gdiplusgraphics-graphics-graphics(constgraphics_)

passing function with parameters to another function

is there a way to pass a function to another function where this passed function would be called inside the second function with the parameters given while passing it. However, the function passed can have different parameters.
I do not want to run the function with data from inside the calling function, just the parameters i passed when calling the function that does the actual call. Basically a periodic check to see if it's ok to continue.
An example of what i'm trying to do:
bool CheckSomething1 (int a, int b) { /* some code */ }
bool CheckSomething2 (int a, int b, int c) { /* some code */ }
bool WaitForTrue ( something funct something.. )
{
while (! funct) {
/* do some work */
}
}
int _tmain(int argc, _TCHAR* argv[])
{
WaitForTrue(CheckSomething1(1, 2));
WaitForTrue(CheckSomething2(1, 2, 3));
return 0;
}
Edit: Basically i'm looking for a way to pass a function with a different number of parameters that can be different types to another function and run it, but the parameters called can be different each time when passing them, but stay the same while in the function to which it is passed.
What you're looking for is std::bind.
See the link above for a brief example of how it works.
Another way you may implement this kind of control style (which is already popular in functional programming, see CPS) is via currying, although it's not-so-easy to express in C++.

cocos2d-x-3.0 draw vs onDraw

I'm using cocos2d-x v3.0 and in some test project I'm doing some custom drawing by overriding Node's draw method, but in the DrawPrimitives example provided they do something like this:
void DrawPrimitivesTest::draw()
{
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}
void DrawPrimitivesTest::onDraw()
{
// drawing code here, why?
}
From reading the header and source files it seems like this may be some way of sending render commands straight to the renderer, is that correct?
Should I be using this method to do custom drawing? What's the difference between draw an onDraw?
EDIT:
As #Pedro Soares mentioned, since Cocos2D-X 3.0 you can't override draw() anymore. you have to use draw(Renderer *renderer, const kmMat4 &transform, bool transformUpdated) instead.
There is sample on cocos2d-x RC0 package that shows how to use the DrawPrimitives on top of other layers.
On your Layer .h add the following:
private:
void onDrawPrimitives(const kmMat4 &transform, bool transformUpdated);
CustomCommand _customCommand;
Now in the cpp of the Layer, override the layer draw method and include the onDrawPrimitives method:
void MyLayer::onDrawPrimitives(const kmMat4 &transform, bool transformUpdated)
{
kmGLPushMatrix();
kmGLLoadMatrix(&transform);
//add your primitive drawing code here
DrawPrimitives::drawLine(ccp(0,0), ccp(100, 100));
}
void MyLayer::draw(Renderer *renderer, const kmMat4& transform, bool transformUpdated)
{
_customCommand.init(_globalZOrder);
_customCommand.func = CC_CALLBACK_0(MyLayer::onDrawPrimitives, this, transform, transformUpdated);
renderer->addCommand(&_customCommand);
}
In future, cocos2d-x 3.x renderer will be multithreaded with command pool.
draw method called by visit method, to create new command. When command is performed by command pool, onDraw is called. At this moment, commands are performed in single thread, but in overloaded onDraw method you should assume, that it will be called in another thread to simplify future migration.
I use draw method for debugDraw Like this It may be helpful
void HelloWorld::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
Layer::draw(renderer, transform, flags);
Director* director = Director::getInstance();
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POSITION );
director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
world->DrawDebugData();
director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
The draw() expression should be the same as the base class function.
The draw method of Node for cocos 3.3rc is:
virtual void draw(Renderer *renderer, const Mat4& transform, uint32_t flags);

Where do I store a function that acts on an array of objects?

I'm trying to create something like the following using c++:
I have a class called particle which will store the position, velocity of each particle. Additionally, a member function will update the particle's position using velocity data.
I'm also trying to write a function that will detect a collision between particles and the boundaries of the box. To do so, this function needs access to each particle's position and velocity. Thus, the function needs to take an entire array of particles as a parameter. However, this function can't exist as a member function of the particle class, because then it won't have access to all the particles.
Question: Where do I include the collision detection function, such that it is an extensible part of the particle class?
I thought about just writing this function inside my main.cpp file, but I haven't the slightest clue whether this adheres to the OOP guidelines. Ideally there might be other functions that also act on an array of particles.
Probably what you want is some sort of "ParticleContainer" object, that holds the array of particles, and performs operations on the particle system as a whole.
(That's also where you would put the code that runs down the array and calls the "Draw" functions.)
I guess that good idea will be to declare a detection function as a friend of class particle: it will have access to all members in class. Then you can fire this function in loop inside of some kind of manager function that will calculate the collision to all particles in array. In this
void CollisionMgr(particleClass *ParticleArrayPtr, int NumOfParticles)
{
while(NumOfParticles)
{
CollisionOfParticle(*ParticleArrayPtr, NumOfParticles);
NumOfParticles--;
}
}
I tend to use a pattern along these lines: Keep all the model state in a single class called Modelor Environment; have a separate class Renderer which knows how to draw the model state; have a System class which ties these together. The following is highly abbreviated, but hopefully gives the idea:
class Box {};
class Location {};
class Particle
{
public:
void updatePosition(double dt);
const Location& getLocation();
};
class Environment
{
public:
void checkForCollisions();
private:
Box box;
std::vector<Particle> particles;
};
class Renderer
{
public:
void render(Environment& environment);
};
class System
{
Environment environment;
Renderer renderer;
};

Is it okay to put game logic in a draw function?

I am making a game, and I have finally finished the gameplay aspect of it, but now it's time for me to create a menu and a high scores screen. I'm not entirely sure how to do it, the game will be in a different state (MENU_STATE, GAMEPLAY_STATE, SCORESCREEN_STATE) and in each state I want to draw different things to the screen, is it okay for me to do something like this then?
draw function()
{
if MENU_STATE
draw menu
if GAMEPLAY_STATE
draw game
if SCORESCREEN_STATE
draw scores
}
I've been following a strictly no logic in the draw function and it's been good so far, but I really can't figure out a different way to do this.
You could use separate classes for the three states, implementing a common interface, and rather than setting a constant for state, set an instance of one of the classes:
interface IState {
void draw();
}
class Menu implements IState {
void draw() {
// Draw menu
}
}
class Game implements IState {
void draw() {
// Draw game
}
}
void draw() {
state.draw();
}
This still isn't ideal (you don't really want drawing code in your state, you want something a bit more separate), but the abstraction is a common one and could be relevant (and it's hard to advise further without knowing more of your architecture).
You are calling some drawing functions in that routine but that doesn't mean
you have to name it draw.
Perhaps this is more appropriate in your case:
// pseudocode
on_game_state function(state)
{
select (state):
MENU_STATE:
draw menu
GAMEPLAY_STATE:
draw game
SCORESCREEN_STATE:
draw scores
}
Using a statemachine would make this simpler. Each state will have its own set of update and draw functions that are called when it is on top of the state stack. Instead of having one draw function with internal state switches you would have Game_Draw(), Menu_Draw(), HighScoreScreen_Draw() etc. Similarly your update functions could be separated out.
static void StateMachine_DrawTopState()
{
switch(stateMachine_topState)
{
case STATE_GAMEPLAY:
{
Gameplay_Draw();
}
break;
case STATE_MENU:
{
Menu_Draw();
}
break;
}
}
Similar to Andrew Aylett's answer and assuming an object-oriented language, perhaps you could do something like:
Interface IState {
void init();
void update();
void draw();
}
class GameplayScene implements IState {
void init() {
// initialize gameplay
}
void update() {
// update game logic
}
void draw() {
// draw game
}
}
class MenuScene implements IState {
void init() {
// initialize menu
}
void update() {
// update menu logic
}
void draw() {
// draw menu
}
}
class ScoresScene etc...
class TitleScene etc...
// Somewhere else, probably in the Game class
void Main() {
// Init game
Scene currentScene = new TitleScene;
while (Scene != null) {
Scene.init();
Scene.update();
Scene.draw();
}
// Exit game
}
You would also need to think about how to handle transition between scenes. You could have each scene class have a member variable called something like nextScene and the main function queries it at the start of the loop to switch to the proper scene.
If you don't have the luxury of using an object-oriented programming language (like C++, Java, C#, Python, etc.), both Colin's and Nick D's answers might help, although I'd try to have the switch statement in one place (say one big game_update function) to allow adding new states by making a change in one place. Alternatively, you could build on the Colin's state machine design to make something more generic and that doesn't explicitly require a hard-coded switch statement. (although to be honest I can't think of a good way to do it at the moment)
It is absolutely not ok to put game logic in a draw function.
However, if it makes your life easier in this specific case, it's ok anyway.
You can always change it later if it becomes a mess.
Yes it's fine, game programmers are allowed to bend the rules for performance gains. The view and the model of a game world are quite often one and the same thing to avoid latency created by decoupling the view and the model.
There's no reason why you can't make the menu and highscores objects part of your game world, it's been done before in quite a few games.