I am trying to assign the instance class to a pointer, how can I do that:
#include <fstream>
using namespace std;
class A
{
private:
static A *pointer;
protected:
A(){}
A GetInstance()
{
//On this point throw the error: could not convert A::pointer’ from A*’ to ‘A’
pointer& = (A)this;
return pointer;
}
};
A *A::pointer = NULL;
How can I do that?
static A *pointer;
...
...
pointer& = (A)this;
Is it possible? I am trying to create a simple repository class with an unique connection instantiated (only one time) and the class repository with the virtuals functions (Add, Save, GetById, GetAll()) inherit from this class, in this way I could create a lot of Repository classes using just only connection without open and close every time. If someone has a example, I would be glad.
Thanks in advanced.
It doesn't work as you tried because (A)this is a conversion from type A * (a pointer to an object of class A) to class A (an object of class A). The compiler cannot do such a conversion.
The type of A::pointer is A *. So is this inside the methods of class A.
All you need is:
pointer = this;
Or, if you want to make more readable, you can write:
A::pointer = this;
This way it's clear for a reader that pointer is a static property (class member) and not an instance property.
You have an error on the next line. The value returned by A::getInstance() (return pointer;) doesn't match the type declared in the method's header (an object of class A). The one that is wrong is the method's declaration. It doesn't make much sense to return an object of type A, it should return a pointer to such an object (more specifically, the only instance of the class, stored in A::pointer.
Change the method's definition like this:
A *GetInstance()
{
pointer = this;
return pointer;
}
As other readers already noticed in comments, it seems you are trying to implement the Singleton pattern (but you are only half-way through it). The best advice about Singleton is to avoid it because it is not testable. It is just a disguised global variable and global variables are, in general, a bad way to store your data.
Related
Note: I do not mean a pointer to an OBJECT or INSTANCE I mean a pointer to a CLASS
I put this at the top because I know if I don't people will tell me that I can do
class MyClass;
MyClass* pointerToMyClass = new MyClass(); // Ta-da! pointer to class!
This is not what I am looking for. I would like to make a pointer to a class type itself, kind of like a function pointer, but for a class.
To make it more clear what I am asking, here is some code that roughly demonstrates what I am looking for.
class MyClass; // real Class
class MyDerived : public MyClass; // derived class
class * ClassPointer = &MyClass; // pointer to my class
MyClass * instanceOfPointer = new ClassPointer(); // now makes an instance of MyClass
ClassPointer = &MyDerived; // pointer to derived class
MyClass * instance2 = new ClassPointer(); // now makes an instance of DerivedClass
So kind of like a typedef, but more dynamic.
I would also want be able to make a vector of class pointers. Currently, I am hacking in the behavior I need with a class function clone() that returns a new pointer to the base class, but I don't particularly like this approach.
Is there anything like this possible in C++?
Edit:
The current problem I am using this for is a polymorphic network protocol.
There is a base packet class:
class packet{
int id=0;
virtual packet* read(); // read packet type into id
virtual packet* clone(){ return new packet(); }
};
then multiple derived packets:
class packet1 : public packet{
int id=1
packet* read(); // do packet specific reading
packet * clone(){ return new packet1(); }
};
class packet2 : public packet{
int id=2
packet* read(); // do packet specific reading
packet * clone(){ return new packet21(); }
};
class packet3 : public packet{
int id=3
packet* read(); // do packet specific reading
packet * clone(){ return new packet3(); }
};
then to read a packet all you have to do is
packet* array[] = { new packet(), new packet1(), new packet2(), new packet3() }; // array of packets, this should be class* if possible
packet type = packet();
type.read(); // read type from network
packet* data = array[type.id].clone(); // pick derived class based on type
data->read(); // read specific packet from network
The packet*[] would be replaced with a class*[] to avoid having to use clone().
This is a simplified but workable example.
No, it's not possible this way because types have to be resolved during compilation. You "physically" compile in instruction how to create new objects. Sure, you can make it variable by simple condition based on typeinfo utilizing RTTI.
#include <typeinfo>
MyClass *createInstanceOf(const std::type_info& myType)
{
if (myType == typeid(MyClass))
return new MyClass();
if (myType == typeid(MyDerived))
return new MyDerived();
// handle invalid type
}
This way you can create different objects based on runtime variable (which is variable std::type_info).
class MyClass;//real Class
class MyDerived: public MyClass;//derived class
std::type_info myType = typeid(MyClass);//pointer to my class
MyClass * instanceOfPointer = createInstanceOf(myType);//now makes an instance of MyClass
myType = typeid(MyDerived);//pointer to derived class
MyClass * instance2 = createInstanceOf(myType);//now makes an instance of DerivedClass
Important part is that this function knows which object creation should be compiled in (all of types you want to support), decision on which path is taken is made in runtime but creation itself is known when you compile the code. Types can never be variable. Even templates are not variable, they generate instances of functions/classes per each type that it was instantiated for during compilation.
I'll add that this solution is useful only in very specific cases. Essentially if you know the type during compilation, then you should never save type_info of the type and then use it in condition to get the type back. It would be much heavier than it should be and is almost impossible to optimize.
Your example seems to be lacking something. As I understand, all you want to do is read type from outside source and then read data based on this variable type. This is quite standard way of reading any outside communication and is done more or less in a way I mentioned above. You need runtime decision mechanism which will take path proper for given type. At some point you'll have to make this decision because your code has to branch out and reach for proper handler (which seems to be packet in your example).
In this case you should not use typeid as it is only guaranteed to be unique and same for the same type in one execution of program - it can't be shared or stored for next execution. In your case you need your own type information (usually enum is most efficient). This way you can create map of your handlers. If types of packets are known and well defined, then you can make them in order from 0 and store them in regular array with constant access time. That's one of most efficient ways to do this. Essentially it would be your type.id.
Best answer was never posed as an answer, credit to Raymond Chen
No you can not take a pointer to a class (and are actually forbidden to take the pointer of a constructor http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf 12.1.12), however you can make a pointer to an abject factory by
template<typename T> T* make<T>() { return new T(); }
and take a function pointer of make<classToPointTo>
Much better than my clone function and I didnt want this wonderful answer burred in the comments for the rest of time.
This is another, "My code isn't working and i don't know why, " question i'm afraid. I just don't have enough knowledge of the stl to know why std::map::insert would throw an exception. If you know what cases it throws an exception, you can probably skip this wall of text and just answer. If you just desperately need some background on the issue, then have at it. I'll post my code and explain what is done, and i would be very grateful if all you with a better knowledge of the stl could explain what could be wrong with my call to insert.
I wrote an object awhile ago that i use occasionally as my go to factory object. It's main purpose is basically to take a string and store both the string and a "create new object function" pointer, so that in the end, you can call a function, pass a string, and if there is a valid registration for it, it returns a new instance of a derived object. Less talk, more code, here's what i got:
factory.h
#ifndef FACTORY_H
#define FACTORY_H
// library tools
#include <map>
#include <string>
// Simplified registration macros
#define DECLARE_DERIVED(T, base) static Factory<base>::DerivedRegister<T> reg;
#define DEFINE_DERIVED(T, base, s) Factory<base>::DerivedRegister<T> T::reg(s);
template<class base>
class Factory
{
protected:
template<class T>
static base * createT() { return new T;}
public:
typedef std::map<std::string, base*(*)()> map_type;
virtual ~Factory(){ }
static base * createInstance(const std::string & s)
{
if(!m_Map.count(s))
return nullptr;
std::map<std::string, base*(*)()>::iterator it = m_Map.find(s);
return it->second();
}
template <class T>
struct DerivedRegister;
protected:
static map_type m_Map;
};
template<class base>
template<class T>
struct Factory<base>::DerivedRegister : public Factory<base>
{
DerivedRegister(std::string const & s)
{
m_Map.insert(std::pair<std::string, base*(*)()>(s, &createT<T>));
}
};
#endif
here's a better explanation of what it does real quick. Let's say you have a base class, class A . and then you have any number of derived classes. I make a factory object somewhere templated to A, and then either create a derived register object manually, or use the macro at the top within the derived classes declaration to create a static registry object. Then you define it in the implementation and call it's constructor, passing in a string to be used to identify the object. using the factory member createInstance you can pass in a string identifier and have a derived object returned, pointed to by an A *.
example:
A.h
class A
{
};
A.cpp
// the map for this factory template has to be defined somewhere, as it is static
Factory<A>::map_type Factory<A>::m_Map;
b.h
#include <A.h>
class B : public A
{
// anywhere in declaration of derived B
DECLARE_DERIVED(A, B)
};
b.cpp
// just somewhere in cpp file
DEFINE_DERIVED(A, B, "B")
main.cpp
int main()
{
A * ptr;
Factory<A> factory;
ptr = factory.createInstance("B");
}
This object has worked for me in the past, mostly without a hitch. Now i'm doing a project a little more complicated. I've taken a liking to the data organization/ api design involved with game engines, and i'm just trying to implement a solution of cataloging, (but not instantiated) shaders, so that you have a whole list of the shaders you've programmed, but they will not be instantiated at run-time unless needed. That aside, this question actually has nothing to do with d3d11, or at least i hope not.
So here is what's going on. I have an object that represents a graphics-shader abstract class. All the shaders you wish to write must derive from this object. The you derive from and implement it's functions differently for all your different shaders.
let's call the base object "SYNC::D3D11Shader" in namespace sync and the derived shaders "ColorShader" "LightShader" and "TextureShader". Since i do not simply want to make an std::map of instances of these shaders within the rendering object, i make a factory within the rendering object like this.
D3D11Renderer.h
class D3D11Renderer
{
// many other members...
Factory<D3D11Shader> m_ShaderFactory;
// many other member...
};
D3D11Renderer.cpp
// define this templated classes map or you'll get undefined errors
Factory<SYNC::D3D11Shader>::map_type Factory<SYNC::D3D11Shader>::m_Map;
and then in the ColorShader i use the macros like so
D3D11ColorShader.h
class D3D11ColorShader : public SYNC::D3D11Shader
{
// ...lotsa members
DECLARE_DERIVED(D3D11ColorShader, SYNC::D3D11Shader)
// lotsa member...
};
D3D11ColorShader.cpp
// define the registery object with it's key here
DEFINE_DERIVED(D3D11ColorShader, SYNC::D3D11Shader, "ColorShader")
this all compiles fine, and where it throws it's exception is where i first call the registryObjects constructor in D3D11ColorShader.cpp, spefically at the insert call. the exception error is this:
Unhandled exception at 0x772315de in Syncopate.exe: 0xC0000005: Access
violation reading location 0x00000004.
So in reality, the question boils down to, when does std::map::insert throw an exception and why. I just knew everyone would be asking for some background on what i'm doing. Low and behold, a giant wall of text has appeared! All i really need is a hunch.
also should i or should i not tag d3d11, because the question doesn't really pertain to it?
Here's a problem:
std::map<std::string, base*(*)()>::iterator it = m_Map.find(s);
return it->second();
if the call to find fails (i,e. it can't find 's' in the map), then it will return m_Map.end(). Dereferencing that is a no-no.
My guess would be that this is due to the order of initialization of static variables. There is no way to control this order. So you are not guaranteed that your initialization:
Factory<A>::map_type Factory<A>::m_Map;
gets called before this initialization:
DEFINE_DERIVED(A, B, "B")
In this case the latter statement must be getting initialized first and so you map has not been allocated.
An alternative design pattern would control the initialization of the singleton factories. If you have an explicit Initialize function on each which creates the factory object then you can call this at the start of your main. E.g.
Factory.h
class Factory {
private:
static Factory* instance_;
public:
static Initialize(){instance_=new Factory;}
Factory* instance(){return instance_;}
}
Factory.cpp
static Factory* Factory::instance_ = NULL;
If you have a lot of factories you will probably want a single initialize function that initializes them all, and you will have to remember to add in the new factories as you create them.
Okay, i have actually been laboring over this error for about a day, and only now do i realize what is wrong.
problem 1:
the derived shaders header was never actually included anywhere throughout the project, and despite the fact that it never needs to be directly instantiated, it still has to be included somewhere so it can be linked and included in build.
problem 2:
interesting enough, just like combinatorial said, the initialization order was not done one after the other, but then looking over my old code, it seemed to initialize correctly before. what the difference here was, i put the factory of the derived objects within a different object then the base class. what i used to do was declare a static function and static factory within the base class so that you could instantiate any of it's registered derived classes from the base class itself. When the factory is included within the base class instead, and instantiation is done through a static function, the initialization order of all the statics seems to be constently in order ( not sure if this is always true). It runs fine now after changing this.
so now, my answer, you can get operating system exceptions like this for trying to use references to objects that were never actually included anywhere in your project. I don't have a very good knowledge of compilers or linkers to tell you why it seemed to compile fine, despite this object never being included. If someone wants to extend my answer, please.
I use MSVC++ 2010 express if that pertains to this predicament.
It appeared that this problem is quite common in our job.
We we are sending an int or enum value through the network, then we receive it we would like to create/call a particular object/function.
The most simply solution would be to use the switch statement, like below:
switch (value) {
case FANCY_TYPE_VALUE: return new FancyType();
}
It works fine, but we would have plenty of these switch blocks, and when we create new value and type, we would need to change all of them. It does seem right.
Other possibility would be to use the templates. But we cannot, since the value of enum is defined in runtime.
Is there any right design pattern for that, or any right approach?
It seems like a very general and common problem in every day coding...
Try a map:
struct Base { };
struct Der1 : Base { static Base * create() { return new Der1; } };
struct Der2 : Base { static Base * create() { return new Der2; } };
struct Der3 : Base { static Base * create() { return new Der3; } };
std::map<int, Base * (*)()> creators;
creators[12] = &Der1::create;
creators[29] = &Der2::create;
creators[85] = &Der3::create;
Base * p = creators[get_id_from_network()]();
(This is of course really crude; at the very least you'd have error checking, and a per-class self-registration scheme so you can't forget to register a class.)
You can actually do this with some template trickery:
#include <map>
template <typename Enum, typename Base>
class EnumFactory {
public:
static Base* create(Enum e) {
typename std::map<Enum,EnumFactory<Enum,Base>*>::const_iterator const it = lookup().find(e);
if (it == lookup().end())
return 0;
return it->second->create();
}
protected:
static std::map<Enum,EnumFactory<Enum,Base>*>& lookup() {
static std::map<Enum,EnumFactory<Enum,Base>*> l;
return l;
}
private:
virtual Base* create() = 0;
};
template <typename Enum, typename Base, typename Der>
class EnumFactoryImpl : public EnumFactory<Enum,Base> {
public:
EnumFactoryImpl(Enum key)
: position(this->lookup().insert(std::make_pair<Enum,EnumFactory<Enum,Base>*>(key,this)).first) {
}
~EnumFactoryImpl() {
this->lookup().erase(position);
}
private:
virtual Base* create() {
return new Der();
}
typename std::map<Enum,EnumFactory<Enum,Base>*>::iterator position;
};
This allows you to create a new derived object from a given enum, by saying
// will create a new `FancyType` object if `value` evaluates to `FANCY_TYPE_VALUE` at runtime
EnumFactory<MyEnum,MyBase>::create(value)
However, you have to have some EnumFactoryImpl objects, which could be static in some function or namespace.
namespace {
EnumFactoryImpl<MyEnum,MyBase,Derived1> const fi1(ENUM_VALUE_1);
EnumFactoryImpl<MyEnum,MyBase,Derived2> const fi2(ENUM_VALUE_2);
EnumFactoryImpl<MyEnum,MyBase,Derived3> const fi3(ENUM_VALUE_3);
EnumFactoryImpl<MyEnum,MyBase,FancyType> const fi1(FANCY_TYPE_VALUE); // your example
}
These lines are the single point where your source code maps enum values to derived types. So you have everything at the same location, and no redundancy (this eliminates the problem of forgetting to change it in some places, when adding new derived types).
One option is to maintain a dictionary of creators(which has the same interface) that can create a concrete type. Now the creation code will search in the dictionary for an int value (resulting from the enum sent from the client) and call the create method, which returns the concrete object via a base-class pointer.
The dictionary can be initialized at one place with the concrete creators corresponding to each possible enum values.
The problem here is that you have to extend this dictionary initialization code when you add a new type of object. A way to avoid is as following.
Let the creator look for a singleton factory instance and register itself in the constructor with the type enums(integers) with which it can create a concret object.
Create a DLL for one/set of creators and have a global instance of the creators.
The name of the DLL can be entered in a config file which is read by the factory in the initialization. The factory loads all the DLLs in this file and this results in the creation of the static objects which registers themselves with the factory.
Now the factory has the map of all the type enums which it can create with the concrete object creators.
The same object creator look-up mechanism is implemented to create the objects.
Now, the factory doesn't need to be extended at all since step 3,4 and 5 doesn't change for new objects introduced. Step 1 can be implemented in one place.
Only thing you need to do is to add a global object for each of the new concrete type which should be there since the C++ doesn't support reflection natively.
kogut, I don't propose this as an answer, but since you ask me to expand on my comment on your original question here's a very brief summary of what the .net environment gives you...
public enum MyEnum
{
[MyAttribute(typeof(ClassNone))]
None,
[MyAttribute(typeof(ClassOne))]
One,
[MyAttribute(typeof(ClassTwo))]
Two,
[MyAttribute(typeof(ClassThree))]
Three
}
So you have your basic enum One, Two, Three etc. which works just like....er....an enum!
But you also code up a class called MyAttribute (and in fact for more information in this area, just search for Attributes). But as you can see this allows you to say, at design time, that such-and-such an enum value is associated with such-and-such a class.
This information is stored in the enum's metadata (the value of a managed environment!) and can be interrogated at runtime (using Reflection). Needless to say this is very powerful, I've used this mechanism to systematically strip out loads of maps of the kind proposed in other answers to your question.
An example of the usefulness is this...at one client I worked with, the convention was to store statuses as strings in a database on the grounds that they would be more readable to a human who needed to run a table query. But this made no sense in the applications, where statuses were pushed through as enums. Take the above approach (with a string rather than a type) and this transform happened on a single line of code as data was read and written. Plus, of course, once you've defined MyAttribute it can be tagged onto any enum you like.
My language if choice these days is c# but this would also be good in (managed) c++.
i have a class with the following structure:
class myClass
{
private:
int type;
classOne objectOne;
classTwo objectTwo;
public:
myClass(classOne object)
{
this->objectOne = object;
this->type = 0;
}
myClass(classTwo object)
{
this->objectTwo = object;
this->type = 1;
}
}
i now want a method returning an object of type classOne if type is 0 and of type classTwo if type is 1. I do not want two methods to achieve this. the classes have different structures.
Is this even possible? Any suggestions are appreciated :)
You can use Boost.Variant to do this. A variant can be constructed directly from any value convertible to one of its bounded types. Similarly, a variant can be assigned any value convertible to one of its bounded types. Heres how you could use it in your class:
class myClass
{
private:
boost::variant<classOne, classTwo> obj;
public:
myClass(classOne object) : obj(object)
{
}
myClass(classTwo object) : obj(object)
{
}
};
It also provides a very convenient boost::get to retrieve the value from the variant.
You can use that to supply code for each bounded type you have(ie classOne and classTwo). Here is an example:
if (classOne * x = boost::get<classOne>(&obj))
{
//Code for classOne
}
else if (classTwo * x = boost::get<classTwo>(&obj)
{
//Code for classTwo
}
However, such code is quite brittle, and without careful attention will likely lead to the introduction of subtle logical errors detectable only at runtime. Thus, real-world use of variant typically demands an access mechanism more robust than get. For this reason, variant supports compile-time checked visitation via apply_visitor. Visitation requires that the programmer explicitly handle (or ignore) each bounded type. Failure to do so results in a compile-time error.
Visitation of a variant requires a visitor object. Like this:
class object_visitor
: public boost::static_visitor<>
{
public:
void operator()(classOne & x) const
{
//Code for classOne
}
void operator()(classTwo & x) const
{
//Code for classTwo
}
};
With the implementation of the above visitor, we can then apply it to obj, as seen in the following:
boost::apply_visitor( object_visitor(), obj );
Unless the two types are related (in which case you can create a function that will return a pointer/reference to the common ancestor) you cannot do that directly in C++.
C++ is a statically typed language, meaning that the type of every expression must be known at compile time, but you are trying to define a function whose return type depends on runtime values.
Depending on the particular problem to solve, there might be different approaches that you could take, including using type erasure (return a boost::any, boost::variant or your own type-erasure).
ClassOne and ClassTwo need to have the same return type then either via inheritance or composition. i.e ClassOne and ClassTwo need to be subclasses of the same super class OR they need to impl the same interface.
I am not sure why you would not use templates for your case.
You can have something like below:
template <class ClassType>
class myClass
{
private:
int type;
ClassType object;
public:
myClass(ClassType object_in)
{
this->object = object_in;
/*
C++ doesn't support reflection so I don't think there
is a robust way of doing the following at runtime.
*/
type = /* Get Type at runtime */;
}
/*
Have another method which return object in a straigtforward way.
*/
};
However, then this become trivial. Any more insight into what your use case is, such that you have to know the type?
Update:
If the ClassType is going to be an Object, you can have a const static int TypeID member for the class, which is set at compile time. You can then use it determine the Type at runtime.
If they're completely different structures, with no common base then an alternative way you can return them from the same function is to use void*.
However that's bad form in C++, usually indicating a design failure - either use two different functions, or use a common base class.
It's apples and oranges. If you put an apple into an recipe that calls for an orange it won't be the same recipe anymore.
The use of type-id is a sign that you need virtual functions for myClass. Even if the other two classes are totally independent, the fact that they are returned by the same function could easily make them inherit a base class. And also you can just return a pair containing class1, class2 and one of them can be null.
The first problem is how you will determine the class of which type has been returned. I think it is possible to return a pointer to structure of this type
struct res {
myClass* c1;
ClassOne* c2;
} ;
The field of the not chosen class is NULL, the other points to the object.
#include <iostream>
using namespace std;
class MyClass
{
public:
void printInformation();
};
void MyClass::printInformation()
{
return;
}
int main()
{
MyClass::printInformation();
fgetc( stdin );
return(0);
}
How would I call the printInformation function within main?
The error tells me that I need to use a class object to do so.
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.
Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.
class MyClass
{
public:
static void printInformation();
};
Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.
Myclass m;
m.printInformation();
// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();
If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)
If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.
If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.
declare it "static" like this:
static void MyClass::printInformation() { return; }
You need to create an object since printInformation() is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
you have to create a instance of the class for calling the method..
On an informal note, you can also call non-static member functions on temporaries:
MyClass().printInformation();
(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))