How to copy instances of an extended CCSprite? - c++

I'm planning to extend the CCSprite class in order to create a Block class, which are the basic building blocks of my game. There may be a number of "archblocks" - prototypes on which individual blocks are to be based. In particular, I want to create a palette, from which the user can pick her building blocks which are to be placed on the game board. Once placed on the board, the building blocks takes on an identity of it's own.
Here's what I have so far:
class Block : public CCSprite {
private:
int _id = 0;
int _type = 0;
public:
Block* CopyBlock();
}
Once a user selects a Block and drops it on the game board, CopyBlock is going to be invoked and the prototype be safely returned to the palette, leaving the newly minted Block living a life of its own on the game board.
I've noticed that CCObject "implements" a Copy method, but as far as I can tell this just refers to a CopyWithZone(0) for CCObject that isn't implemented. The Copy method isn't virtual, though, so I'm a little unsure if I'm able to override this. (I'm not super strong in C++ but I do have a good grasp on OOP, so I'm up for the details if anyone care to share.)
Question:
1) Does this design make sense? Should I go with overriding Copy and/or CopyWithZone instead?
2) How can I implement CopyBlock (or Copy and/or CopyWithZone) so that both CCSprite stuff and members like _type are copied to the new Block?
Thanks!

Unless your block sprite contains children. You can easily create a copy constructor, creating the same sprite and copying the block's attributes (and maybe some needed sprite attributes) by yourself :
class Block : public CCSprite {
private:
int _id = 0;
int _type = 0;
public:
Block (Block &otherBlock);
}
Implementation file :
Block::Block (Block &otherBlock) {
this->initWithTexture(otherBlock.getTexture());
// If your sprite contains children then this is the place to iterate all children
// sprites, create and add them to this block. (do not forget to copy their position as well.)
this->_id = otherBlock._id;
this->_type = otherBlock._type;
}
Note that since initWithTexture does not copy the texture, if you tweak the texture it will be visible on all copies of blocks but if you don't have texture tweaking needs then this should work for you.

Related

How do I use a C++ unique_ptr in a vector?

TLDR: I think I'm using unique_ptr wrongly, but I'm not sure how to do this otherwise.
I am trying to write a simple physics engine wrapped up in an entity component system. The physics world is essentially the main manager class for all objects that are affected by physics, that should contain all physics properties for entities in the world(ideally stored in a std::vector). In every update loop, after the engine solves constraints, it iterates through the vector of physics objects stored in the physics world and applies the forces, accelerations, impulses etc.
There is also a SceneManager that stores more general entities (eg. for rendering etc) and a SceneEntity which stores behaviour specific components.
I chose to use vector<unique_ptr> for storage because there should only be one instance of each entity (physics or scene) - the end user can handle the raw pointer and pass it to functions etc, but the lifetime of the entities themselves are handled by the SceneManager and PhysicsWorld.
The general structure is as follows:
class PhysicsWorld
{
private:
unique_ptr<PhysicsEntity> entities;
public:
void addEntity(PhysicsEntity * entity)
{
unique_ptr<PhysicsEntity> entity_ptr(entity);
entities.push_back(std::move(entity_ptr));
}
}
class PhysicsEntity
{
private:
unsigned int id;
float gravity;
public:
Entity();
~Entity();
void setGravity(float val);
}
PhysicsWorld world{};
PhysicsEntity * physent = new PhysicsEntity{};
physent->setGravity(3.0f);
world.addEntity(physent)
SceneManager scene{};
RigidbodyComponent * rbcomp = new Rigidbody{ent};
SceneEntity * sceneEnt = new SceneEntity{};
sceneEnt->addComponent(rbcomp);
scene->addEntity(sceneEnt);
My problem is that when I run this code, I get an error from xutility saying "attempting to reference a deleted function" - I believe it occurs somwhere around world.addEntity(). After much searching, I've concluded that this is due to my use of unique_ptr. Is this error occurring because unique_ptr is not the right tool for the job, or am I missing something - or is the error elsewhere?
The issue was that I had not defined move constructors and move assignment operators for PhysicsWorld, so it was using the default ones, which in turn were calling the (deleted) copy constructors for the PhysicsEntity stored in the vector. The code compiled after I defined those.

Going up the object hierarchy

Hi so I've got some nice tree hierarchy of objects in program i'm working on. I've came across a problem with communicating the bottom to top way. How I have it set up right now is that in every constructor I pass a reference to object creating the new object. Simple structure would look like this:
[Controller] -> [World] -> [Object]
Going up one layer (from world to controller or from object to world) is OK. But where the problem starts to occur is when I try to go up 2 layers.
Here is a simplified structure of how I have set it up:
Controller.h:
#include "World.h"
Class Controller {
public:
Controller() {
_worlds.push_back(World(*this));
)
void update() { // Called on a loop from main program loop
_worlds[0].update(); // Calls update of active world, in this case world[0]
}
vector<World> _worlds;
Camera _camera; // class with checkIfInView function
}
World.h:
#Include "Object.h"
Class Controller;
Class World {
World(Controller& ref) : _controller(ref) {
_objects.push_back(Object(*this));
_controller._camera.doStuff(); // works OK
}
void update() {
for (auto& i : _objects)
i.update();
}
vector<Object> _objects;
Controller& _controller;
}
Object.h:
Class World;
Class Object {
Object(World& ref) : _world(ref) {}
void update();
World& _world;
}
Object.cpp:
#include "Controller.h"
#include "World.h"
void Object::update() {
_world._controller._camera.checkIfInView(*this); // Read access violation
}
Controller hold one single camera object which is responsible for what is being shown. What I need is a way for Objects to call checkIfInView to know if they should render or not. Is there any other way to do this or a way to fix it?
EDIT: Updated code.
The problem
Let's look at your nice chain, starting with the Controller constructor. As it's the top object of your hierarchy, it the start of the construction. I imagine that in main() you have something like
Controller c;
This will cause the constructor to be called:
Controller() {
_worlds.push_back(World(*this)); // !!!
}
World(*this) will create a new temporary world that you'll push into the vector of worlds of your controller. The temporary object only exists for the time of the expression in which it appears.
The temporary World will then be constructed with
World(Controller& ref) : _controller(ref) { // ref to controller is kept
_objects.push_back(Object(*this)); // ouch!!!
_controller._camera.doStuff(); // works OK
}
Now an object will be created which refers to *this world. Ouch!! Remember that that world is temporary ? At the end of the construction it will be deleted, so that all objects will refer to a C++ object that no longer exists and hence the UB which happen to produce the segmentation fault in your case.
The start of a solution
The design that you have is quite delicate. Think twice if you couldn't find a safer design pattern. If you want nevertheless to pursue in this direction, avoid creating objects using temporary items: create dynamically allocated ones instead.
Controller() {
_worlds.push_back(*new World(*this)); // !!! risk of leakage
}
The next thing would be to use pointers instead of references:
Controller() {
_worlds.push_back(new World(*this)); // risk of leakage
}
Of course, you'd need to change the rest of the code accordingly, to work with pointers.
The next thing would be to opt for shared pointers: this avoids risk of leakage:
Controller() {
_worlds.push_back(make_shared<World>(*this)); // risk of leakage
}
In the adaptation of your code you'd then need to make a difference between shared_ptr in your vectors, which refers to the object, and weak_ptr to the parten objects, to indicate tha the parent is now shared owned by the child but by another object.
A better solution ?
I warn you that it will not be a piece of cake. As soon as you have pointers, you'd need to take care of the rule of 3 for each class.
Many issues arise from:
1) the nested construction -> may be worth considering the builder design pattern
2) the risk of mixing of static objects and dynamically created objects, never knowing which kind is the parent. -> may be worth using a protected/private constructor and use a factory method for making sure that all objects are always dynamic objects.

Engine to render different types of graphic objects

I'm trying to write a class (some sort of graphics engine) basically it's purpose is to render ANYTHING that I pass into it. In most tutorials I've seen, objects draw themselves. I'm not sure if that's how things are supposed to work. I've been searching the internet trying to come up with different ways to handle this problem, I've been reviewing function templates and class templates over and over again (which sounds like the solution I could be looking for) but when I try using templates, it just seems messy to me (possibly because I don't fully understand how to use them) and then I'll feel like taking the template class down, then I'll give it a second try but then I just take it down again, I'm not sure if that's the way to go but it might be. Originally it was tiled-based only (including a movable player on screen along with a camera system), but now I've trying to code up a tile map editor which has things such as tool bars, lists, text, possibly even primitives on screen in the future, etc. and I'm wondering how I will draw all those elements onto the screen with a certain procedure (the procedure isn't important right now, I'll find that out later). If any of you were going to write a graphics engine class, how would you have it distinguish different types of graphic objects from one another, such as a primitive not being drawn as a sprite or a sphere primitive not being drawn as a triangle primitive, etc.? Any help would be appreciated. :)
This is the header for it, it's not functional right now because I've been doing some editing on it, Just ignore the part where I'm using the "new" keyword, I'm still learning that, but I hope this gives an idea for what I'm trying to accomplish:
//graphicsEngine.h
#pragma once
#include<allegro5\allegro.h>
#include<allegro5\allegro_image.h>
#include<allegro5\allegro_primitives.h>
template <class graphicObjectData>
class graphicsEngine
{
public:
static graphicObjectData graphicObject[];
static int numObjects;
static void setup()
{
al_init_image_addon();
al_init_primitives_addon();
graphicObject = new graphicObjectData [1]; //ignore this line
}
template <class graphicObjectData> static void registerObject(graphicObjectData &newGraphicObject) //I'm trying to use a template function to take any type of graphic object
{
graphicObject[numObjects] = &newObject;
numObjects++;
}
static void process() //This is the main process where EVERYTHING is supposed be drawn
{
int i;
al_clear_to_color(al_map_rgb(0,0,0));
for (i=0;i<numObjects;i++) drawObject(graphicObject[i]);
al_flip_display();
}
};
I am a huge fan of templates, but you may find in this case that they are cumbersome (though not necessarily the wrong answer). Since it appears you may be wanting diverse object types in your drawing container, inheritance may actually be a stronger solution.
You will want a base type which provides an abstract interface for drawing. All this class needs is some function which provides a mechanism for the actual draw process. It does not actually care how drawing occurs, what's important is that the deriving class knows how to draw itself (if you want to separate your drawing and your objects, keep reading and I will try to explain a way to accomplish this):
class Drawable {
public:
// This is our interface for drawing. Simply, we just need
// something to instruct our base class to draw something.
// Note: this method is pure virtual so that is must be
// overriden by a deriving class.
virtual void draw() = 0;
// In addition, we need to also give this class a default virtual
// destructor in case the deriving class needs to clean itself up.
virtual ~Drawable() { /* The deriving class might want to fill this in */ }
};
From here, you would simply write new classes which inherit from the Drawable class and provide the necessary draw() override.
class Circle : public Drawable {
public:
void draw() {
// Do whatever you need to make this render a circle.
}
~Circle() { /* Do cleanup code */ }
};
class Tetrahedron : public Drawable {
public:
void draw() {
// Do whatever you need to make this render a tetrahedron.
}
~Tetrahedron() { /* Do cleanup code */ }
};
class DrawableText : public Drawable {
public:
std::string _text;
// Just to illustrate that the state of the deriving class
// could be variable and even dependent on other classes:
DrawableText(std::string text) : _text(text) {}
void draw() {
// Yet another override of the Drawable::draw function.
}
~DrawableText() {
// Cleanup here again - in this case, _text will clean itself
// up so nothing to do here. You could even omit this since
// Drawable provides a default destructor.
}
};
Now, to link all these objects together, you could simply place them in a container of your choosing which accepts references or pointers (or in C++11 and greater, unique_ptr, shared_ptr and friends). Setup whatever draw context you need and loop through all the contents of the container calling draw().
void do_drawing() {
// This works, but consider checking out unique_ptr and shared_ptr for safer
// memory management
std::vector<Drawable*> drawable_objects;
drawable_objects.push_back(new Circle);
drawable_objects.push_back(new Tetrahedron);
drawable_objects.push_back(new DrawableText("Hello, Drawing Program!"));
// Loop through and draw our circle, tetrahedron and text.
for (auto drawable_object : drawable_objects) {
drawable_object->draw();
}
// Remember to clean up the allocations in drawable_objects!
}
If you would like to provide state information to your drawing mechanism, you can require that as a parameter in the draw() routine of the Drawable base class:
class Drawable {
public:
// Now takes parameters which hold program state
virtual void draw(DrawContext& draw_context, WorldData& world_data) = 0;
virtual ~Drawable() { /* The deriving class might want to fill this in */ }
};
The deriving classes Circle, Tetrahedron and DrawableText would, of course, need their draw() signatures updated to take the new program state, but this will allow you to do all of your low-level drawing through an object which is designed for graphics drawing instead of burdening the main class with this functionality. What state you provide is solely up to you and your design. It's pretty flexible.
BIG UPDATE - Another Way to Do It Using Composition
I've been giving it careful thought, and decided to share what I've been up to. What I wrote above has worked for me in the past, but this time around I've decided to go a different route with my engine and forego a scene graph entirely. I'm not sure I can recommend this way of doing things as it can make things complicated, but it also opens the doors to a tremendous amount of flexibility. Effectively, I have written lower-level objects such as VertexBuffer, Effect, Texture etc. which allow me to compose objects in any way I want. I am using templates this time around more than inheritance (though intheritance is still necessary for providing implementations for the VertexBuffers, Textures, etc.).
The reason I bring this up is because you were talking about getting a larger degree of seperation. Using a system such as I described, I could build a world object like this:
class World {
public:
WorldGeometry geometry; // Would hold triangle data.
WorldOccluder occluder; // Runs occlusion tests against
// the geometry and flags what's visible and
// what is not.
WorldCollider collider; // Handles all routines for collision detections.
WorldDrawer drawer; // Draws the world geometry.
void process_and_draw();// Optionally calls everything in necessary
// order.
};
Here, i would have multiple objects which focus on a single aspect of my engine's processing. WorldGeometry would store all polygon details about this particular world object. WorldOccluder would do checks against the camera and geometry to see which patches of the world are actually visible. WorldCollider would process collission detection against any world objects (omitted for brevity). Finally, WorldDrawer would actually be responsible for the drawing of the world and maintain the VertexBuffer and other lower-level drawing objects as needed.
As you can see, this works a little more closely to what you originally asked as the geometry is actually not used only for rendering. It's more data on the polygons of the world but can be fed to WorldGeometry and WorldOccluder which don't do any drawing whatsoever. In fact, the World class only exists to group these similar classes together, but the WorldDrawer may not be dependent on a World object. Instead, it may need a WorldGeometry object or even a list of Triangles. Basically, your program structure becomes highly flexible and dependencies begin to disappear since objects do not inherit often or at all and only request what they absolutely require to function. Case in point:
class WorldOccluder {
public:
// I do not need anything more than a WorldGeometry reference here //
WorldOccluder(WorldGeometry& geometry) : _geometry(geometry)
// At this point, all I need to function is the position of the camera //
WorldOccluderResult check_occlusion(const Float3& camera) {
// Do all of the world occlusion checks based on the passed
// geometry and then return a WorldOccluderResult
// Which hypothetically could contain lists for visible and occluded
// geometry
}
private:
WorldGeometry& _geometry;
};
I chose the WorldOccluder as an example because I've spent the better part of the day working on something like this for my engine and have used a class hierarchy much like above. I've got boxes in 3D space changing colors based on if they should be seen or not. My classes are very succinct and easy to follow, and my entire project hierarchy is easy to follow (I think it is anyway). So this seems to work just fine! I love being on vacation!
Final note: I mentioned templates but didn't explain them. If I have an object that does processing around drawing, a template works really well for this. It avoids dependencies (such as through inheritence) while still giving a great degree of flexibility. Additionally, templates can be optimized by the compiler by inlining code and avoiding virtual-style calls (if the compiler can deduce such optimizations):
template <typename TEffect, TDrawable>
void draw(TEffect& effect, TDrawable& drawable, const Matrix& world, const Matrix& view, const Matrix& projection) {
// Setup effect matrices - our effect template
// must provide these function signatures
effect.world(world);
effect.view(view);
effect.projection(projection);
// Do some drawing!
// (NOTE: could use some RAII stuff here in case drawable throws).
effect.begin();
for (int pass = 0; pass < effect.pass_count(); pass++) {
effect.begin_pass(pass);
drawable.draw(); // Once again, TDrawable objects must provide this signature
effect.end_pass(pass);
}
effect.end();
}
My technique might really suck, but I do it like this.
class entity {
public:
virtual void render() {}
};
vector<entity> entities;
void render() {
for(auto c : entities) {
c->render();
}
}
Then I can do stuff like this:
class cubeEntity : public entity {
public:
virtual void render() override {
drawCube();
}
};
class triangleEntity : public entity {
public:
virtual void render() override {
drawTriangle();
}
};
And to use it:
entities.push_back(new cubeEntity());
entities.push_back(new triangleEntity());
People say that it's bad to use dynamic inheritance. They're a lot smarter than me, but this approach has been working fine for a while. Make sure to make all your destructors virtual!
The way the SFML graphics library draws objects (and the way I think is most manageable) is to have all drawable objects inherit from a 'Drawable' class (like the one in David Peterson's answer), which can then be passed to the graphics engine in order to be drawn.
To draw objects, I'd have:
A Base class:
class Drawable
{
int XPosition;
int YPosition;
int PixelData[100][100]; //Or whatever storage system you're using
}
This can be used to contain information common to all drawable classes (like position, and some form of data storage).
Derived Subclasses:
class Triangle : public Drawable
{
Triangle() {} //overloaded constructors, additional variables etc
int indigenous_to_triangle;
}
Because each subclass is largely unique, you can use this method to create anything from sprites to graphical-primitives.
Each of these derived classes can then be passed to the engine by reference with
A 'Draw' function referencing the Base class:
void GraphicsEngine::draw(const Drawable& _object);
Using this method, a template is no longer necessary. Unfortunately your current graphicObjectData array wouldn't work, because derived classes would be 'sliced' in order to fit in it. However, creating a list or vector of 'const Drawable*' pointers (or preferably, smart pointers) would work just as well for keeping tabs on all your objects, though the actual objects would have to be stored elsewhere.
You could use something like this to draw everything using a vector of pointers (I tried to preserve your function and variable names):
std::vector<const Drawable*> graphicObject; //Smart pointers would be better here
static void process()
{
for (int i = 0; i < graphicObject.size(); ++i)
draw(graphicObject[i]);
}
You'd just have to make sure you added each object to the list as it was created.
If you were clever about it, you could even do this in the construction and destruction:
class Drawable; //So the compiler doesn't throw an error
std::vector<const Drawable*> graphicObject;
class Drawable
{
Triangle() {} //overloaded constructors, additional variables etc
int indigenous_to_triangle;
std::vector<const Drawable*>::iterator itPos;
Drawable() {
graphicObject.push_back(this);
itPos = graphicObject.end() - 1;
}
~Drawable() {
graphicObject.erase(itPos);
}
}
Now you can just create objects and they'll be drawn automatically when process() is called! And they'll even be removed from the list once they're destroyed!
All the above ideas have served me well in the past, so I hope I've helped you out, or at least given you something to think about.

What is a good design for this situation?

I am making a basic render engine.
In order to let the render engine operate on all kinds of geometry,
I made this class:
class Geometry
{
protected:
ID3D10Buffer* m_pVertexBuffer;
ID3D10Buffer* m_pIndexBuffer;
public:
[...]
};
Now, I would like the user to be able to create his own geometry by inheriting from this class.
So let's suppose the user made a class Cube : public Geometry
The user would have to create the vertexbuffer and indexbuffer at initialisation.
This is a problem, since it would recreate the vertexbuffer and indexbuffer each time a new Cube object is made. There should only be one instance of vertexbuffer and indexbuffer per derived class. Either that, or a completely different design.
A solution might be to make separate static ID3D10Buffer* for the inheriting class , and set the pointers of the inherited class equal to those in the constructor.
But that would require a static method like static void CreateBuffers() which the user would have to call explicitly one time in his application for each type he decides to make that inherits from Geometry. That doesn't seem like a nice design.
What is a good solution to this problem?
You should separate the concept of an instance from the concept of a mesh. This means you create one version of the Geometry for a cube that represents the vertex and index buffer for a cube.
You then introduce a new class called GeometryInstance which contains a transformation matrix. This class should also have a pointer/reference to a Geometry. Now you can create new Instances of your geometry by creating GeometryInstances that all refer the same Geometry object not duplicating memory or work when creating a new box.
EDIT:
Given that you have the Geometry class from the question and a Mesh class as in your comment your Mesh class should look something like this:
class Mesh {
private:
Matrix4x4 transformation;
Geometry* geometry;
public:
Mesh(const Matrix4x4 _t, Geometry* _g) : transformation(_t), geometry(_g) {}
}
Now when creating your scene you want to do things like this
...
std::vector<Mesh> myMeshes;
// OrdinaryGeometry is a class inheriting Geometry
OrdinaryGeometry* geom = new OrdinaryGeometry(...);
for(int i = 0; i < ordinaryGeomCount; ++i) {
// generateTransform is a function that generates some
// transformation Matrix given an index, just as an example
myMeshes.push_back(Mesh(generateTransform(i), geom);
}
// SpecialGeometry is a class inheriting Geometry with a different
// set of vertices and indices
SuperSpecialGeometry* specialGeom = new SuperSpecialGeometry(...);
for(int i = 0; i < specialGeomCount; ++i) {
myMeshes.push_back(Mesh(generateTransform(i), specialGeom);
}
// Now render all instances
for(int i = 0; i < myMeshes.size(); ++i) {
render(myMeshes[i]);
}
Note how we only have two Geometry objects that are shared between multiple Meshes. These should ideally be refcounted using std::shared_ptr or something similar but it's outside the scope of the question.
What would be the point of sub classing Geometry in your cube example? A cube is simply an instance of Geometry which has a certain set of triangles and indices. There would be no difference between a Cube class and a Sphere class, other than that they fill their triangle/index buffers with different data. So the data itself is what is important here. You need a way to allow the user to provide your engine with various shape data, and to then refer to that data in some way once its made.
For providing shape data, you have two options. You can decide to either keep the details of Geometry private, and provide some interface that takes raw data like a string from a file, or a float array filled in some user made function, creates a Geometry instance for that data, and then gives the user some handle to that instance (or allow the user to specify a handle). Or, you can create some class like GeometryInfo which has methods addTriangle, addVertex etc which the user fills him/herself, and then have some function that accepts a GeometryInfo, creates a Geometry instance for that data and then gives the user some handle again.
In both situations you need to provide some interface that allows the user to say "here's some data, make something out of it and give it some handle. Minimally it would have a function as I described. You would need to maintain a map somewhere of created Geometry instances in your engine. This is so you enforce your one instance per shape rule, and so you can associate what the user wants ("Ball", "Cube") with what your engine needs (Geometry with filled buffers).
Now about the handle. I would either let the user associate the data with a name, like "Ball", or return some integer that the user would then associate with a certain "Ball" instance. That way when you make your Rocket class, the user can then request the "Ball" instance from your engine, various other objects can use the "Ball" and everything's fine because they're just storing handles, not the ball itself. I wouldn't advise storing a pointer to the actual Geometry instance. The mesh doesn't own the geometry, because it can share it with other meshes. It doesn't need access to the geometry's members, because the renderer handles the grunt work. So it is an unnecessary dependency. The only reason would be for speed, but using hashing for your handles would work just as good.
Now for some examples:
Providing shape data:
//option one
engine->CreateGeometryFromFile("ball.txt", "Ball");
//option two
GeometryInfo ball;
ball.addTriangle(0, 1, 0, 1);
ball.addTriangle(...);
...
engine->CreateGeometryFromInfo(ball, "Ball");
Refering to that data using a handle:
class Drawable
{
std::string shape;
Matrix transform;
};
class Rocket : public Drawable
{
Rocket() { shape = "Ball";}
//other stuff here for physics maybe
};
class BallShapedEnemy : public Drawable
{
BallShapedEnemy() { shape = "Ball";}
...
}
...
...in user's render loop...
for each (drawable in myDrawables)
{
engine->Render(drawable.GetShape(), drawable.GetTransform());
}
Now, having a separate class for each different game object such as Rocket is debatable, and is the subject of another question entirely, I was just making it look like your example from a comment.
This may be a sloppy way of doing it but could you not just make a singleton?
#pragma once
#include <iostream>
#define GEOM Geometry::getInstance()
class Geometry
{
protected:
static Geometry* ptrInstance;
static Geometry* getInstance();
float* m_pVertexBuffer;
float* m_pIndexBuffer;
public:
Geometry(void);
~Geometry(void);
void callGeom();
};
#include "Geometry.h"
Geometry* Geometry::ptrInstance = 0;
Geometry::Geometry(void)
{
}
Geometry::~Geometry(void)
{
}
Geometry* Geometry::getInstance()
{
if(ptrInstance == 0)
{
ptrInstance = new Geometry();
}
return ptrInstance;
}
void Geometry::callGeom()
{
std::cout << "Call successful!" << std::endl;
}
Only problem with this method is you would only ever have one Geometry object and I'm assuming you might want more than one? If not it could be useful, but I think Lasserallan's method is probably a much better implementation for what your looking for.

C++ Having trouble with syntax, so a class can pass data to other classes

I'm not having a lot of luck in C++ getting one of my classes to see/reference/copy data from one of my other classes so it can use it.
Basically I get the error 'Core' does not name a type or when I try to forward declare (http://stackoverflow.com/questions/2133250/does-not-name-a-type-error-in-c) I get field 'core' has incomplete type
I'm guessing the second error is due to the class not really being initialized possibly, so it has nothing to get? I dunno :( (see code at the bottom)
In my C# games I would normally create a "core" class, and then within that I would start other classes such as 'entities', 'player', 'weapons', etc. When I start these other classes I would pass "this"
public WeaponManager c_WeaponManager;
...
c_WeaponManager = new WeaponManager(this);
so I could always access public values of any class from anywhere as long as it passed through core.
Eg:
So when I do my update through the 'weapon' class, and it detects its hit the player, I'd simply get a function within that class to...
core.playerClass.deductHealth(damageAmmount);
..or something like that.
It allowed me to keep lots of variables I wanted to access globally neatly tucked away in areas that I felt were appropriate.
I know this isn't a good method of programming, but its what I'm fairly comfortable with and I mainly do hobby programming so I like being able to access my data quickly without bureaucratic Get() and Set() functions handing data from one class to another and another. Also I'm still fumbling my way through header files as they seem to be a pain in the ass
//-----------[In vid_glinit.h]-------------------
include "core.h"
class Vid_glInit
{
public:
RECT glWindowRect;
Core core;
Vid_glInit();
~Vid_glInit();
void StartGl(HWND _hGameWindow, int resolutionX, int resolutionY);
private:
};
//------------[in core.h]----------
include "vid_glinit.h"
class Core
{
public:
Vid_glInit vid_glinit(this);
enum GAME_MODE
{
INIT,
MENUS,
GAMEPLAY
};
GAME_MODE gameMode;
HWND hGameWindow;
HGLRC hGameRenderContext; // Permanent Rendering Context
HDC hGameDeviceContext; // Private GDI Device Context
//functions go here
Core();
~Core();
void testFunc();
void Run();
void Update();
void Render();
void StartGl(int resoultionX, int resolutionY);
private:
};
The goal is that when I start OpenGl, instead of having lots of little functions to pass data around I simply tell the glFunctions who need the Device or Rendering context to use core.hGameDeviceContext , if that makes sense
The problem is that you've got
class Vid_glInit
{
public:
Core core;
which means allocate a full copy of the Core object inline inside this class, and also
class Core
{
public:
Vid_glInit vid_glinit(this);
which means allocate a full copy of the Vid_glInit object inline inside the class - and this is now circular, and neither structure's size can be computed.
You probably actually want to allocate at least one of them by reference or pointer, i.e.
class Core
{
public:
Vid_glInit* vid_glinit; // pointer: access properties as core.vid_glinit->foo
Vid_glInit& vid_glinit; // reference: properties are core.vid_glinit.foo
In that case you can use the class Vid_glInit; simple forward declaration because these are just pointers internally and the size of a pointer is fixed regardless of the structure behind it, i.e. C++ can lay out the Core class in memory without full knowledge of the Vid_glInit structure.