Polymorphism with new data members - c++

I would like to write a function that can initialize and return objects of different classes using polymorphism. I also would like these classes to have different data members which may be called through the virtual function. What I wrote below might work. Could you check if I have some undefined behavior in there? Thank you! One thing I am worried about is that when I call "delete polypoint" at the end it will not free the data member "scale" that is unique to "CRectangle". If my code doesn't work is there a way to make it work?
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int scale;
int area ()
{ return (width * height * scale ); }
};
CPolygon *polytestinner()
{
CPolygon *polypoint = 0;
int consoleinput = 2;
if (consoleinput>1)
{
CRectangle *rectpoint = new CRectangle();
rectpoint->scale = 4;
polypoint = rectpoint;
}
polypoint->set_values(3,4);
return polypoint;
}
void polytest()
{
CPolygon *polypoint = polytestinner();
gstd::print<int>(polypoint->area());
delete polypoint;
}
int main()
{
polytest();
return 0;
}
Thank you!

I feel compelled to point out Andrei Alexandrescu's object factory architecture. It allows your architecture to grow without having to modify the factory every time you create a concrete type. It is based on a "callback register", and it is actually implemented as a generic component in some libraries. The code is below.
Live Code Example
#include<map>
#include<iostream>
#include<stdexcept>
// your typical base class
class Shape {
public:
virtual void Draw() const = 0;
// virtual destructor allows concrete types to implement their own
// destrucion mechanisms
virtual ~Shape() {}
};
// this factory architecture was suggested by Andrei Alexandrescu in
// his book "Modern C++ Design" --- read it to get the full
// explanation (and a more generic implementation); this is just an
// example
class ShapeFactory {
public:
// this typedef allows to "name" arbitrary functions which take no
// arguments and return a pointer to a Shape instance
typedef Shape* (*CreateShapeCallback)();
Shape* CreateShape(int ShapeId) {
// try to find the callback corresponding to the given shape id;
// if no shape id found, throw exception
CallbackMap::const_iterator it = m_callbacks.find(ShapeId);
if(it == m_callbacks.end()) {
throw std::runtime_error("unknown shape id");
} else {
// create the instance using the creator callback
return (it->second)();
}
}
bool RegisterShape(int ShapeId, CreateShapeCallback Creator) {
// returns true if shape was registered; false if it had already
// been registered
return m_callbacks.insert(CallbackMap::value_type(ShapeId, Creator)).second;
}
bool UnRegisterShape(int ShapeId) {
// returns true if shape was unregistered, false if it was not
// registered in the first place
return m_callbacks.erase(ShapeId) == 1;
}
private:
// the typedef simplifies the implementation
typedef std::map<int, CreateShapeCallback> CallbackMap;
// the callbacks are stored in a map int->callback (see typedef
// above)
CallbackMap m_callbacks;
};
// create some concrete shapes... you would do this in other CPP files
class Line : public Shape {
public:
void Draw() const {
std::cout<<"Drawing a line"<<std::endl;
}
};
// another concrete shape...
class Circle : public Shape {
public:
void Draw() const {
std::cout<<"Drawing a circle"<<std::endl;
}
};
// ... other concrete shapes...
enum ShapeIds {LINE=1, CIRCLE, COUNT};
Shape* CreateLine() { return new Line; }
Shape* CreateCircle() { return new Circle; }
int main() {
// suppose this is the "singleton" instance for the ShapeFactory
// (this is an example! Singletons are not implemented like this!)
ShapeFactory *factory = new ShapeFactory;
factory->RegisterShape(ShapeIds::LINE, CreateLine);
factory->RegisterShape(ShapeIds::CIRCLE, CreateCircle);
Shape* s1 = factory->CreateShape(ShapeIds::CIRCLE);
Shape* s2 = factory->CreateShape(ShapeIds::LINE);
s1->Draw();
s2->Draw();
// will throw an error
try {
Shape *s3 = factory->CreateShape(-1);
s3->Draw();
} catch(const std::exception& e) {
std::cout<<"caught exception: "<<e.what()<<std::endl;
}
return 0;
}

CPolygon needs a virtual destructor:
virtual ~CPolygon() {}

You have undefined behavior in your code:
CPolygon *polypoint;
delete polypoint;
deleting a base class pointer when there is no virtual destructor will result in undefined behavior.
Your CPolygon class and CRectangle classes have no destructors, though the compiler will generate default destructor for you in this case, but they are not virtual by default. Therefore, you need to at least define a virtual destructor for your base class, i.e., CPolygon.

Related

c++ Inheritance and shared pointers

Here is the situation. Let's say we have a virtual base class (e.g. ShapeJuggler) which contains a method that takes a shared pointer to a virtual base class object (e.g. Shape) as argument. Let's jump into the following pseudo-code to understand:
class Shape {
}
class ShapeJuggler {
virtual void juggle(shared_ptr<Shape>) = 0;
}
// Now deriving a class from it
class Square : public Shape {
}
class SquareJuggler : public ShapeJuggler {
public:
void juggle(shared_ptr<Shape>) {
// Want to do something specific with a 'Square'
// Or transform the 'shared_ptr<Shape>' into a 'shared_ptr<Square>'
}
}
// Calling the juggle method
void main(void) {
shared_ptr<Square> square_ptr = (shared_ptr<Square>) new Square();
SquareJuggler squareJuggler;
squareJuggler.juggle(square_ptr); // how to access 'Square'-specific members?
}
make_shared or dynamic/static_cast don't seem to do the job.
Is it at all possible? Any ideas, suggestions?
Thanks
This is where std::dynamic_pointer_cast (or one of its friends) comes into play.
It's just like dynamic_cast, but for std::shared_ptrs.
In your case (assuming the Shape class is polymorphic so dynamic_cast works):
void juggle(shared_ptr<Shape> shape) {
auto const sq = std::dynamic_pointer_cast<Square>(shape);
assert(sq);
sq->squareSpecificStuff();
}
This is the multiple dispatch problem. Their are many solution to this problem, the cleanest might be using the visitor pattern, but if you just have one function that need multiple dispatch you could avoid using a visitor:
class SquareJuggler;
class TriangleJuggler;
//.... others concrete jugglers.
class Shape {
//The default behaviour for any juggler and any shape
virtual void juggle_by(Juggler& t) {
//default code for any shape an juggle
}
// list each juggler for which you may
// implement a specific behavior
virtual void juggle_by(SquareJuggler& t) {
//provides default behavior in case you will not
// create a specific behavior for a specific shape.
//for example, just call the unspecific juggler:
this->Shape::juggle_by(static_cast<Juggler&>(t));
}
virtual void juggle_by(TriangleJuggler& t) {
//provides default behavior in case you will not
//create a specific behavior for a specific shape.
//for example, just call the unspecific juggler:
this->Shape::juggle_by(static_cast<Juggler&>(t));
}
//...
};
// Now deriving a class from it
class Square : public Shape {
void juggle_by(SquareJuggler& s) override{
//code specific to SquareJuggler and Shape
}
};
class Triangle : public Shape {
void juggle_by(TriangleJuggler& t) override{
//code specific to TriangleJuggler and Shape
}
};
class ShapeJuggler {
virtual void juggle(shared_ptr<Shape> s) {
//by default (if default has sense):
s->juggle_by(*this);
}
};
class SquareJuggler: public ShapeJuggler {
public:
void juggle(shared_ptr<Shape> s) override {
s->juggle_by(*this);
}
};
class TriangleJuggler: public ShapeJuggler {
public:
void juggle(shared_ptr<Shape> s) override {
s->juggle_by(*this);
}
};
// Calling the juggle method
void main(void) {
shared_ptr<Square> square_ptr = (shared_ptr<Square>) new Square();
SquareJuggler squareJuggler;
squareJuggler.juggle(square_ptr);
//This last call, will perform two virtual calls:
// 1. SquareJuggler::juggle(shared_ptr<Shape);
// 2. Square::juggle_by(SquareJuggler&);
}
You could also defines your XXXJuggler as final, which will enable some devirtualization optimization.

Event-based Game engine based on polymorphism of Entities

I would like to create a simple framework for throwing and catching events in a game. Events could be things like a Collision which (according to the type) can take several arguments (note that every Event type may take another amount of arguments, not just two as in the example).
I would then like to implement functions/classes/... to deal with a Collision, based on polymorphism. This example should illustrate the problem:
#include <iostream>
#include <vector>
class Entity {};
class Player: public Entity {};
class Bomb: public Entity {
public:
bool exploded;
};
class MineSweeper: public Entity {};
// For now, I only included Collisions, but I eventually want to extend it to
// more types of Events too (base class Event, Collision is derived class)
void onCollision(Player* p, Bomb* b) {
if (! b->exploded) {
std::cout << "BOOM";
b->exploded = true;
}
}
void onCollision(Entity* e, Entity* f) {
std::cout << "Unhandled collision\n";
}
// Possibility for Collision between Minesweeper and Bomb later
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() {
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
onCollision(board[0], board[1]); // player and bomb!
onCollision(board[1], board[2]);
}
};
int main() {
Game g;
g.main_loop();
}
Note that I understand perfectly well why the above code doesn't work as intended, I included this example solely to illustrate my problem better.
The above example uses functions for the events, but I'm perfectly fine with classes or any other solution that is maintainable.
I hope it is clear that I would like C++ to decide which event handler to use based on the types of the arguments (presumably at runtime).
My question: How can I do this in C++? An example would be appreciated.
(not my question: fix my code please)
user2864740 provided enough clues for me to find a solution myself. Multiple dispatch was indeed the missing piece.
The following code works as intended, making use of dynamic_cast to dispatch correctly.
#include <iostream>
#include <vector>
class Entity {
virtual void please_make_this_polymorphic() {}
// although this function does nothing, it is needed to tell C++ that it
// needs to make Entity polymorphic (and thus needs to know about the type
// of derived classes at runtime).
};
class Player: public Entity {};
class Bomb: public Entity {
public:
bool exploded;
};
class MineSweeper: public Entity {};
// For now, I only included Collisions, but I eventually want to extend it to
// more types of Events too (base class Event, Collision is derived class)
void onCollision(Player* p, Bomb* b) {
if (!b->exploded) {
std::cout << "BOOM\n";
b->exploded = true;
}
}
void onCollision(Entity* e, Entity* f) {
std::cout << "Unhandled collision\n";
}
void dispatchCollision(Entity* e, Entity* f) {
Player* p = dynamic_cast<Player*>(e);
Bomb* b = dynamic_cast<Bomb*>(f);
if (p != nullptr && b != nullptr) {
onCollision(p, b); // player and bomb
} else {
onCollision(e, f); // default
}
}
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() {
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
dispatchCollision(board[0], board[1]); // player and bomb
dispatchCollision(board[1], board[2]);
}
};
int main() {
Game g;
g.main_loop();
}
Although it works, I'd like to point out some problems with this code:
Manual editing of dispatchCollision needed when adding new Collisions.
Currently, the dispatcher using a simple kind of rule-based system. (Does it fit rule 1? What about rule 2? ...) When adding loads of different functions it needs to dispatch, that may have an impact on the performance.
A collision between A and B should be the same as a collision between B and A, but that isn't properly handled yet.
Solving these problems is not necessarily in the scope of this question IMHO.
Also, the example given should work just as well for more than 2 arguments. (Multiple dispatch, not just double dispatch.)
You should decide first what event subscription model you need.
It could be signal/slot mechanism and you can find plenty of libraries:
https://code.google.com/p/cpp-events/ , http://sigslot.sourceforge.net/ and the like.
Or it could be bubbling/sinking events like in HTML DOM when event gets propagated on parent/child chain ( from event source element to its containers).
Or even other schema.
It is quite easy to create whatever you need with std::function holders in modern C++.
Maybe a good structure for your case could be something like this:
class Entity{
public:
virtual int getType() = 0;
};
enum EntityTypes {
ACTOR,
BOMB,
MINESWEEPER,
};
class Actor : public Entity{
public:
virtual int getType() {return int(ACTOR);}
void applyDamage() {
std::cout << "OUCH";
}
};
class Bomb : public Entity{
public:
Bomb() : exploded(false) {}
virtual int getType() {return int(BOMB);}
void explode() {
this->exploded = true;
}
bool isExploded() {
return this->exploded;
}
protected:
bool exploded;
};
class MineSweeper : public Entity{
public:
virtual int getType() {return int(MINESWEEPER);}
};
class CollisionSolver {
public:
virtual solve(Entity* entity0, Entity* entity1) = 0;
};
class ActorBombCollisionSolver : public CollisionSolver {
public:
virtual solve(Entity* entity0, Entity* entity1) {
Actor* actor;
Bomb* bomb;
if (entity0->getType() == ACTOR && entity1->getType() == BOMB) {
actor = static_cast<Actor*>(entity0);
bomb = static_cast<Bomb*>(entity1);
}else if (entity1->getType() == ACTOR && entity0->getType() == BOMB) {
actor = static_cast<Actor*>(entity1);
bomb = static_cast<Bomb*>(entity0);
}else {
//throw error;
}
if (!bomb->isExploded()) {
bomb->explode();
actor->applyDamage();
}
}
};
class CollisionDispatcher {
public:
CollisionDispatcher() {
CollisionSolver* actorBombCollisionSolver = new ActorBombCollisionSolver;
this->solvers[ACTOR][BOMB] = actorBombCollisionSolver;
this->solvers[BOMB][ACTOR] = actorBombCollisionSolver;
// this part wouldn't be necessary if you used smart pointers instead of raw... :)
this->solvers[BOMB][MINESWEEPER] = 0;
this->solvers[MINESWEEPER][BOMB] = 0;
this->solvers[ACTOR][MINESWEEPER] = 0;
this->solvers[MINESWEEPER][ACTOR] = 0;
}
void dispatchCollision(Entity* entity0, Entity* entity1) {
CollisionSolver* solver = this->solvers[entity0->getType()][entity1->getType()];
if (!solver) {
return;
}
solver->solve(entity0, entity1);
}
protected:
unordered_map<int, unordered_map<int, CollisionSolver*> > solvers;
};
class Game {
public:
std::vector<Entity*> board; // some kind of linear board
Game() : dispatcher(new CollisionDispatcher)
{
board = {new Player, new Bomb, new MineSweeper};
}
void main_loop() {
dispatcher->dispatchCollision(board[0], board[1]);
dispatcher->dispatchCollision(board[0], board[2]);
dispatcher->dispatchCollision(board[1], board[2]);
}
protected:
CollisionDispatcher* dispatcher;
};
int main() {
Game g;
g.main_loop();
}
This way you can easily add new collision solvers, just define the class, and register t in the CollisionDispatcher constructor.
If you use smart pointers you won't need to set zeroes in the map entries not registered, but if you use raw pointers you have to set them to zero OR use unordered_map::find method instead of just grabbing the solver using operator []
Hope it helps!

Is a big switch block unavoidable in C++ due to lack of reflection [duplicate]

This question already has answers here:
Is there a way to instantiate objects from a string holding their class name?
(12 answers)
Closed 9 years ago.
Assume I have a hierarchy of classes:
class Shape {
};
class Circle : public Shape {
}
class Square : public Shape {
}
... hundreds of other shapes continue on...
When given the name of a shape class as a string, I need to instantiate objects of that class.
In java, I can do something like this (pseudo code!)
Shape createShape(String name) {
return new Class.forName(name);
}
But in C++, I have to do this: (pseudo code!)
Shape * createShape(const string &name) {
if (name.compare("Circle") == 0) {
return new Circle();
}
else if (name.compare("Square") == 0) {
return new Square();
}
else if ... //hundreds of else if continues, one for each shape
}
Is there any better way in C++ to handle situation like this?
It's avoidable using the factory pattern, but you still need a bunch of boilerplate code to get off the ground. For example:
// Class factory functions -- these could also be inlined into their respective
// class definitions using a macro
Shape *createCircle() { return new Circle(); }
Shape *createSquare() { return new Square(); }
// etc.
// Create a map from type name to factory
typedef std::map<std::string, Shape *(*)()> ShapeFactoryMap;
ShapeFactoryMap factoryMap;
factoryMap["Circle"] = &createCircle;
factoryMap["Square"] = &createSquare;
// etc.
Then, when you want to instantiate an object, you can do this:
ShapeFactoryMap::iterator factory = factoryMap.find("Circle");
if (factory != factoryMap.end())
{
Shape *circle = factory->second(); // Creates a Circle instance
...
}
else
{
// Handle error
}
Whether this is better than just doing a series of if/else... string comparisons is not clear, since it depends on what exactly you're doing to be doing with this.
I second Adam Rosenfield's solution using maps. However, a lower level interface to get your higher level functionality is to use a dlsym() lookup.
Assume that your generic Shape interface lies in the file Shape.hpp and has the following form:
class Shape {
public:
virtual ~Shape () {}
//...virtual methods
virtual void draw () const = 0;
};
template <typename DERIVED>
class ShapeBridge : public Shape {
public:
static Shape * create () { return new DERIVED; }
};
struct ShapeFactory {
Shape * (*create) ();
};
Suppose you wanted to add a new shape dynamically by creating a new shared object, and then linking it dynamically into your existing running executable. Then, you can now create an abstract factory of sorts, which uses dynamic loading of shared objects to obtain the concrete factory functions:
#include <string>
#include <map>
#include <dlfcn.h>
struct ShapeCreator {
void *dlhandle_;
void *factory_;
ShapeCreator () : dlhandle_(0), factory_(0) {}
void open (std::string libname) {
dlhandle_ = dlopen(libname.c_str(), RTLD_LAZY);
factory_ = dlsym(dlhandle_, "factory");
}
void close () { if (dlhandle_) dlclose(dlhandle_); }
ShapeFactory * factory () const {
return static_cast<ShapeFactory *>(factory_);
}
static Shape * create (std::string name) {
static std::map<std::string, ShapeCreator> lookup;
static std::string dir = "./";
if (lookup[name].factory() == 0) {
lookup[name].open(dir + name + ".so");
}
return lookup[name].factory()->create();
}
};
Your shared object could have the following implementation:
// gcc -fPIC -shared -Wl,-export-dynamic -o Circle.so Circle.cpp -lc
#include "Shape.hpp"
#include <iostream>
class Circle : public ShapeBridge<Circle> {
public:
//..
void draw () const { std::cout << "I am a circle.\n"; }
};
extern "C" {
ShapeFactory factory = { Circle::create };
}
Then to dynamically create the shape:
Shape *s = ShapeCreator::create("Circle");
s->draw();
Of course, the example is a little more interesting if it actually obtained its name dynamically (like from a configuration file, or from a user input).
The main difference is that unlike Java, C++ doesn't have an in-built function like forName(String), which does the task for you. In C++ you have to implement it.
Now it's important how you do that stuff. The proposed way of switch/case is one way, which is straight forward but lengthy way. You can automate the things:
(1) First introduce an intermediate template class, which creates an object, so that you don't have to implement method for each and every class.
template<class Derived>
class ShapeCreator : public Shape { // This class automates the creations
public:
static Shape* Create () {
new Derived(); // Assuming that no-argument default constructor is avaialable
}
};
class Circle : public ShapeCreator<Circle> {
};
class Square : public ShapeCreator<Square> {
};
//... and so on
(2) Now inside the class Shape, introduce one static std::map, which holds a handle to every derived class.
class Shape {
public:
typedef std::map<std::sting, Shape* (*)()> ShapeMap;
static ShapeMap s_ShapeMap;
static Shape* Create (const std::string name) {
ShapeMap::iterator it = s_ShapeMap.find(name);
if(it == s_ShapeMap.end())
return 0;
it->second();
}
};
(3) Populating s_ShapeMap has to be done statically, you can choose to do it before the main() is called (be careful while doing this) or as the first function inside the main(). Use preprocessor trick to automate the things:
#define INIT(SHAPE) Shape::s_ShapeMap[#SHAPE] = &SHAPE::Create
Shape* InitializeShapeMap () {
INIT(Circle);
INIT(Square);
INIT(Triangle);
// ...
}
#undef INIT
Whenever any new shape is introduced, then just add it as an INIT inside the function.
C++ is a 'class based' language which means the structure of a class is only known at compile time. Hence you cannot generate a type at runtime.
It's better to avoid that sort of class instanciation unless you only know the class name at runtime.
If need to do that at large scale, have a look at third-party code generators such as jinja.
It'll help you create a factory off a template and a given mapping "string" -> "class name".
There's no way to do what you want the way it is in Java, but there are ways to make it slightly less painful than a giant switch statement. You will need some kind of factory. Personally I like to use something along these lines:
class ShapeBase
{
};
template<class TShape>
class Shape: public ShapeBase
{
public:
typedef TShape shape_type;
template< class TFactory >
static void registerClass(TFactory* factory)
{
factory->registerShape(shape_type::name(), [](){ return new shape_type(); });
}
};
class Circle: public Shape<Circle>
{
public:
static const char* name() { return "Circle"; }
};
class Square: public Shape<Square>
{
public:
static const char* name() { return "Square"; }
};
class ShapeFactory
{
private:
typedef std::function<ShapeBase*()> shape_creator;
std::map<std::string,shape_creator> _creators;
public:
ShapeFactory()
{
registerShapes();
}
void registerShapes()
{
Square::registerClass(this);
Circle::registerClass(this);
}
void registerShape( const std::string& name, shape_creator creator )
{
_creators[name] = creator;
}
ShapeBase* create(const std::string& name)
{
return _creators[name]();
}
};
int main( int argc, char** argv )
{
ShapeFactory factory;
ShapeBase* circle = factory.create("Circle");
ShapeBase* square = factory.create("Square");
return 0;
}
If you can get away with defining all of your Shape objects in an executable component or dynamic library, rather than a static library, then there are tricks that you can use to auto-register your classes with a singleton factory, but I think it's a better idea to do it this way and avoid the singleton.
There is no support for what you are asing in the language. Nevertheless you can use the following pattern to streamline your design:
class Shape
{
Shape *CreateShape(const char *name)
{
// Iterate single linked list of known derived classes.
Node *item = ListOfDerivedClasses;
while (item != NULL)
{
if (strcmp(item->name, name) == 0)
return item->factory();
item = item->next;
}
}
typedef Shape *CreateShapeInstance();
struct Node
{
char *name;
CreateShapeInstance *factory;
Node *next;
Node(char *n, CreateShapeInstance *f)
{
name = n; factory = f;
next = Shape::ListOfDerivedClasses;
Shape::ListOfDerivedClasses = this;
}
};
static Node *ListOfDerivedClasses;
};
class Circle : public Shape
{
static Shape *CreateInstance() { return new Circle(); }
}
static Shape::Node circle_info("Circle", Circle::CreateInstance);
The idea is that the single linked list that contains only static elements is created during initialization of static objects and it is never modified after that. This design allows adding derived classes without modifying the base class while CreateShape in the base class can create any derived class that registered itself in the list.

Select subclass from base class...possible?

I am learning C++ and I am stuck with a problem. I need a way to use a specific subclass within base class. Does it make sense or I am using a wrong approach? SelectBrand should select the subclass, how can I do it?
Here below my simplified classes:
-----
class Protocol {
public:
Protocol() {};
~Protocol() {};
int openPort();
int readPort(char *buffer);
.....
private:
Protocol (const Protocol&);
};
int Protocol::openPort() {......};
int Protocol::readPort() {.........};
/***********************************************************************************/
class Device{
public:
Device(Protocol& port):_protocol(port){}
~Device();
virtual int getEvent(char *buffer) { return -1; }
int Device::selectBrand();
..............
protected:
Protocol& _protocol;
private:
int brand;
Device(const Device&orig);
};
Device::~Device() {}
int Device::selectBrand() {
......
switch (X)
case 1:
"use subclass Brand_B"
case 2:
"use subclass Brand_B"
.......
}
/***********************************************************************************/
class Brand_A:public Device {
public:
Brand_A(Protocol& port);
~Brand_A();
int getEvent(void *rawData);
private:
Brand_A(const Brand_A&);
};
Brand_A::Brand_A(Protocol& port):Device(port) {}
Brand_A::~Brand_A() {}
int Brand_A::getEvent(void *rawData) {
.... readPort(......);
}
/***********************************************************************************/
class Brand_B:public Device {
public:
Brand_B(Protocol& port);
~Brand_B();
int getEvent(void *rawData);
private:
Brand_B(const Brand_B&);
};
Brand_B::Brand_B(Protocol& port):Device(port) {}
Brand_B::~Brand_B() {}
int Brand_B::getEvent(void *rawData) {
.... readPort(......);
}
/* main **********************************************************/
int main(int argc, char **argv) {
Device *mydev;
char *buffer;
..............
mydev->selectBrand();
..........
mydev->getEvent(buffer);
...........
}
This is not a good idea.
Generally the answer is dynamic_cast, but invoking specific behavior of descendants from a base class is usually a bad design sign.
You can try inverting the class hierarchy and using templates.
I figured I should flesh out the comment I made above. First of all, you can check out the Wikipedia page for more information on the abstract factory pattern. Basically it allows you to access different implementations of an interface, with the implementation used determined at runtime. However, you still don't know which implementation you're getting as that is decided in the factory method that returns the implementation of the interface. As a result, you can only ever use the members in the interface and not a specific implementation. An example that uses your classes above would be something like:
class Device
{
virtual int getEvent(void *rawData) = 0;
}
class BrandA : public Device
{
// define constructors/destructors etc.
int getEvent(void *rawData)
{
// BrandA's implementation for getEvent
}
}
class BrandB : public Device
{
// define constructors/destructors etc.
int getEvent(void *rawData)
{
// BrandB's implementation for getEvent
}
}
class DeviceFactory
{
static Device *CreateDevice(/*any parameters for determining the device?*/)
{
// You probably don't want to randomly determine which implementation you use...
if ((rand() % 2) == 0)
{
return new BrandA();
}
else
{
return new BrandB();
}
}
}
int main()
{
// CreateDevice will decide which type of device we use, however we can only
// explicitly reference the members of the base class (Device).
Device *myDevice = DeviceFactory::CreateDevice();
myDevice->getEvent();
return 0;
}
It looks like you might be trying to implement something like polymorphism when C++ will do that for you. If you define virtual methods in your base class and override them in your sub classes, calls to those methods on a pointer or reference to the base type should result in the sub class' implementation being called.
For example:
class BaseClass
{
virtual void DoSomething()
{
printf("base");
}
};
class SubClass : public BaseClass
{
void DoSomething()
{
printf("sub");
}
};
int main()
{
BaseClass *myBase = new SubClass();
myBase->DoSomething(); // should print "sub" to stdout
return 0;
}
You have to know what derived type (type of subclass) you want to use when you create it so that the instance has the added functionality of the derived type. If you don't, all you get is the functionality of the base class, and you cannot treat it as anything but the base class (or anything further up the inheritance hierarchy if your base class inherits from something).
You may even want to use a member to differentiate between different instances if they're not actually doing anything different. It's hard to tell from the code example exactly what you want to do. Maybe a more specific example of what you're trying to achieve rather than how you're trying to achieve it would help.
please, let me reformulate the problem. I have 1 baseClass and some subclasses; Brand_A....Brand_N
Now, in the main() I don't know in advance which subclass I will use; this selection is demanded to a function in the baseClass which I called selectBrand. What I need is a mechanism to select and use the right subclass based on internal conditions. I want to masquerade to the main() the selected subclass. How to get this?
I implemented and tested this code; it works fine. Is it good design or can be done better?
class BehaviorBase
{
public:
virtual ~BehaviorBase() {}
virtual void DoSomethingOn(Object* obj) {}
};
class Object
{
public:
BehaviorBase* behavior;
void DoSomething();
void ChangeBehavior(int param);
~Object();
}
class BehaviorA: public BehaviorBase
{
void DoSomethingOn(Object* obj)
{
printf("Behavior A\n");
}
};
class BehaviorB: public BehaviorBase
{
string other_data;
void DoSomethingOn(Object* obj)
{
printf("Behavior B\n");
}
};
void Object::DoSomething()
{
behavior->DoSomethingOn(this);
}
Object::~Object()
{
delete behavior;
}
void Object::ChangeBehavior(int param)
{
delete behavior;
switch(param)
{
case 1: behavior = new BehaviorA; break;
case 2: behavior = new BehaviorB; break;
}
}
int main(int argc, char **argv) {
int param=1;
Object *obj;
obj= new Object;
obj->ChangeBehavior(param);
obj->DoSomething();
delete obj;
return(0);
}

C++ Derived Class problems

I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.
The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.
Here is the function:
// Tell each screen to draw itself.
//gsElement is a GameScreen iterator
//gsScreens is a list of type GameScreen
void Draw()
{
for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++)
{
/*if (gsElement->ssState == Hidden)
continue;*/
gsElement->Draw();
}
}
Here are a copy of my classes:
class GameScreen {
public:
string strName;
bool bIsPopup;
bool bOtherScreenHasFocus;
ScreenState ssState;
//ScreenManager smScreenManager;
GameScreen(string strName){
this->strName = strName;
}
//Determine if the screen should be drawn or not
bool IsActive(){
return !bOtherScreenHasFocus &&
(ssState == Active);
}
//------------------------------------
//Load graphics content for the screen
//------------------------------------
virtual void LoadContent(){
}
//------------------------------------
//Unload content for the screen
//------------------------------------
virtual void UnloadContent(){
}
//-------------------------------------------------------------------------
//Update changes whether the screen should be updated or not and sets
//whether the screen should be drawn or not.
//
//Input:
// bOtherScreenHasFocus - is used set whether the screen should update
// bCoveredByOtherScreen - is used to set whether the screen is drawn or not
//-------------------------------------------------------------------------
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
this->bOtherScreenHasFocus = bOtherScreenHasFocus;
//if the screen is covered by another than change the screen state to hidden
//else set the screen state to active
if(bCoveredByOtherScreen){
ssState = Hidden;
}
else{
ssState = Active;
}
}
//-----------------------------------------------------------
//Takes input from the mouse and calls appropriate actions
//-----------------------------------------------------------
virtual void HandleInput(){
}
//----------------------
//Draw content on screen
//----------------------
virtual void Draw(){
}
//--------------------------------------
//Deletes screen from the screen manager
//--------------------------------------
void ExitScreen(){
//smScreenManager.RemoveScreen(*this);
}
};
class MenuScreen: public GameScreen{
public:
vector <BUTTON> vbtnMenuEntries;
MenuScreen(string strName):GameScreen(strName){
}
virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){
vbtnMenuEntries[i].IsPressed();
}
}
virtual void Draw(){
GameScreen::Draw();
for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++)
vbtnMenuEntries[i].Draw();
}
};
class testMenu : public MenuScreen{
public:
vector<OBJECT> test;
//OBJECT background3();
// OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40);
// BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test());
bool draw;
testMenu():MenuScreen("testMenu"){
OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768);
OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40);
test.push_back(background3);
test.push_back(testPic);
//background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height)
//test.push_back(background3);
// vbtnMenuEntries.push_back(x);
draw = false;
}
void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){
MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen);
//cout << "X" << endl;
/*if(MouseLButton == true){
testMenu2 t;
smManager.AddScreen(t);
}*/
}
void Draw(){
//background3.Draw();
test[0].Draw();
test[1].Draw();
MenuScreen::Draw();
///*if(draw){*/
// testPic.Draw();
//}
}
/*void test(){
draw = true;
}*/
};
If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it.
What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list.
C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.
To get the polymorphic behavior you're after and at the same time use a std::vector<>, you must store pointers to the base class type in the vector, instead of storing values. Also, you must remember to free their memory before the vector goes out of scope.
For instance:
#include <vector>
#include <algorithm>
struct Base
{
virtual void Foo() = 0;
virtual ~Base() { }
};
struct Derived1 : public Base
{
void Foo() { }
};
struct Derived2 : public Base
{
void Foo() { }
};
struct delete_ptr
{
template <typename T>
void operator()(T& p)
{
delete p;
p = 0;
}
};
int wmain(int, wchar_t*[])
{
std::vector<Base*> items;
items.push_back(new Derived1);
items.push_back(new Derived2);
Base& first = items.front();
first.Foo(); // Will boil down to Derived1::Foo().
Base& last = items.back();
last.Foo(); // Will boil down to Derived2::Foo().
std::for_each(items.begin(), items.end(), delete_ptr())
};
Curt is absolutely correct, but I'd just like to throw a little more information at it.
This problem (storing base-class objects, rather than pointers) is sometimes called "slicing".
Also, I tend to make use of the following macro:
#define DISALLOW_COPYING(X) \
private: \
X(const X &); \
const X& operator= (const X& x)
Then you put this somewhere in your class definition:
class Foo {
// ...
DISALLOW_COPYING(Foo);
};
If another class attempts to copy the object, you'll get a compiler error (because the methods are declared private). If the class itself attempts to copy the object, you'll get a linker error (because the methods have no implementation).
Boost (www.boost.org, a library I would recommend anyone coding in C++ use) provides a noncopyable base class that does exactly that; you don't need an ugly macro that way.