Class Members Over Exports - c++

When Using DLLs or Code-injecting to be Specific
this is an example class only intended for explaining
class test
{
int newint1;
char newchararray[512];
void (*newfunction1)( int newarg1 );
int newfunction2( bool newarg1, char newarg2 )
{
return newint1;
}
} mynewclass1;
that covers most common elements that's included in classes
now when exporting this function to another DLL or application
and missed an element of those, either data member or function member, private or public
what happens or changed their order ?
and if each function is assigned it's value when Code-Injecting like
mynewclass1.newfunction1 = (void *)(newexportedfunction);
what's the happens in this case, if members of the class are pointers that are assigned after class construction and then missed one member or changed their order ?

I suppose that you forget to add a public: (:)
mynewclass1 is a statically initialized to zero at load time (unless you are working on very old version of windows).
if you add a constructor to your class behavior will become unpredictable because it is quite difficult to know when the static is effectively initialized (link-time dependencies at least).

Related

How to access the variable from another function in a class

So I have experience using programming languages and just switched over to C++. Now I have created a few working applications but I always stumble upon the same problem. I don't exactly know what everything is called in the code. You have a class which obvious to see since the has written class before it. And you also have some sort of functions attached to the class are these called instances? And is the class the object it referring to by for example class::function.
But my main question was how can I access the variables from another function within the same class file. I have included an example below explaining what I want to achieve. I already tried a lot of things and googled a lot. I tried code pasting code creating setting and getting functions, calling the class to get and set the variable but I can't get it to work. I've spend a lot of time fixing this very basic problem. Could someone explain me what is called what in this code (Class,Object,Instance). And explain me the most efficient way to receive data from another function in the same .cpp file.
Thanks
load_data.h
#pragma once
class load_data
{
public:
static int data[13];
load_data();
static void test2();
};
load_data.cpp
#include "load_data.h"
#include "abc.h"
load_data::load_data()
{
int data[3]; // Initializing the array
data[0] = abc::LoadImage("textures/1.png");
data[1] = abc::LoadImage("textures/2.png");
data[2] = abc::LoadImage("textures/3.png");
}
void load_data::test2()
{
abc::CreateSprite(1, data[0]);
abc::SetSpritePosition(1, 0, 0);
abc::SetSpriteScale(1, 3, 3);
// Now I get an error saying it has no data. Which however is set in
// load_data(). But since each function gets its own variables this one will be empty.
abc::CreateSprite(2, data[1]);
abc::SetSpritePosition(2, 64, 64);
abc::SetSpriteScale(2, 3, 3);
abc::CreateSprite(3, data[2]);
abc::SetSpritePosition(3, 128, 128);
abc::SetSpriteScale(3, 3, 3);
}
Change your load_data() constructor to the following (currently, your creating a new data[] variable that is locally scoped to your load_data() constructor, which gets initialized instead of your object's data[] (gets "eclipsed"). Your subsequent call to test2() fails when it accesses data[] because the other, local data[] was initialized instead. Also, fyi, the local data[] is destroyed when load_data() returns (because it is an auto/stack variable that falls out of scope).
load_data::load_data()
{
//int data[3]; // Initializing the array
data[0] = abc::LoadImage("textures/1.png");
data[1] = abc::LoadImage("textures/2.png");
data[2] = abc::LoadImage("textures/3.png");
}
you also have some sort of functions attached to the class are these
called instances?
An object is an instance of a class. A class defines the object type, which consists of state variables, and operations for them (known as "member functions" or "methods").
An object's methods are called through a handle to the instance. IE, an instantiated variable:
load_data ld = new load_data();
ld.test2();
And is the class the object it referring to by for example
class::function.
This notation is for explicitly qualifying a method name. It helps resolve naming conflicts and should only be used when needed (otherwise it is implicit).
But my main question was how can I access the variables from another
function within the same class file.
...
But since each function gets its own variables this one will be empty
All functions of a class share the class'es (member) variables. An given instance of the class has the only copy of those member variables (ie, their specific values/memory to that instance), so all method calls through a specific instance variable (say ld) of load_data will refer to the same data[] array (so load_data ld1, ld2 would each have their own copies). Functions can, and usually do, declare their own variables to help assist in computing the task they perform (bools, counters, etc...). These such variables, as mentioned before, are scoped to that function, meaning they're no longer allocated and get destroyed when the function returns (they are auto-variables).
And you also have some sort of functions attached to the class are
these called instances?
No. the functions inside of the class are called "class member function" or just "member functions". An instance is a copy of that object (read class) in memory. So in short:
class A {
public:
void fun (void); ///< This is a class member function
};
void main (int argc, char *argv[]) {
A a; ///< a is an instance of object A
}
And is the class the object it referring to by for example
class::function.
The class defines the object. In the above snipped, A is an object.
But my main question was how can I access the variables from another
function within the same class file.
You need to do some reading on variable scope. In your above example the data array is local to the constructor. It doesn't exist within the object, only within that function. So as soon as the constructor finishes, the variable goes out of scope and is lost. In order to keep it in the object's scope you would need to declare it within the object.
class load_object {
public:
// The same
private:
int load[3];
};
Cheers

Pattern to register metatypes in Qt

Introduction
I've got a library, which registers a bunch of metatypes, illustrated by this code:
abstractfoobase.h
namespace foo {
enum FooState { OK, MAYBE };
class AbstractFooBase : public QObject {...};
}
Q_DECLARE_METATYPE(foo::FooState)
There is also a corresponding abstractfoobase.cpp, contents depending on what exactly is implemented in base class.
foousingclass.h:
namespace foo {
class FooUsingClass : public AbstractFooBase {...};
}
Again there is corresponding foousingclass.cpp, which has method implementations etc.
Now, that Q_DECLARE_METATYPE enables the type for Qt template classes and QVariant. To enable using the type in queued signals and such, there also needs to be a corresponding call:
qRegisterMetaType<foo::FooState>();
Question
What is(are) the good place(s) to put the qRegisterMetaType call? I obviously don't want any expllicit initialization call from application code. The registrations must have happened after doing a foo::FooUsingClass *f = new foo::FooUsingClass();.
In Java I'd put this kind of code in a static initialization block. I can see several ways to do this in C++ too, but none of them seem particularily nice. For example, simply putting these to AbstractFooBase constructor will cause the registrations being called every time a subclass instance is created, which may be undesired overhead. So those who have done this, where did you put the qRegisterMetaType calls?
I've recently discovered a simple solution, which works with static libraries as well.
It exploits the fact that qMetaTypeId<>() is used throughout Qt's meta type system. So, with an explicit template instantiation, we can enforce linkage to abstractfoobase.cpp (otherwise the linker might decide not to if there are no referenced symbols) and ensure that the type is registered statically at program startup:
abstractfoobase.h
#include <QMetaType>
namespace foo {
enum FooState { OK, MAYBE };
}
Q_DECLARE_METATYPE(foo::FooState)
extern template int qMetaTypeId<foo::FooState>();
abstractfoobase.cpp
static const int kFooStateMetaTypeId = qRegisterMetaType<foo::FooState>();
template int qMetaTypeId<foo::FooState>();
I can imagine something as following:
in abstractfoobase.cpp:
namespace foo {
/// Initializer
class FooStateInit {
public:
FooStateInit() {
qRegisterMetaType<foo::FooState>();
}
};
static FooStateInit fooStateInit;
} // namespace foo
If your type will be instantiated frequently, you could use a function static initialization in the constructor:
struct OftenInstantiatedDataType
{
OftenInstantiatedDataType()
{
static const int reg = qRegisterMetaType<OftenInstantiatedDataType>();
}
};
Q_DECLARE_METATYPE(OftenInstantiatedDataType);
Pros:
Lazy registration - will only be called if your type is instantiated at all
Single registration - will only be called once, no matter how often your type is instantiated
Cons:
Makes executable larger
In the few apps I created I used to simply register them in main()-like function that defines the application's startup. Of course, that separates the registration from the .cpp/.h file, but in turn it guarantees that I will not fall into some name-collisions (I see all names/types in one place) and also guarantees that the regs are done exactly one single time: app startup ;)
But, that's not a.. 'handy' way.. if anyone has better way, I'd like to see it too.

What is the rationale for not having static constructor in C++?

What is the rationale for not having static constructor in C++?
If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:
//illegal C++
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
//illegal constructor!
static sample()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
};
In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.
So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!
Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.
Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:
//called before main()
int static_main() {
ClassFoo();
ClassBar();
}
with appropriate declarations:
class ClassFoo {
static int y;
ClassFoo() {
y = 1;
}
}
class ClassBar {
static int x;
ClassBar() {
x = ClassFoo::y+1;
}
}
So the answer is, there is no reason it isn't there, at least not a technical one.
This doesn't really make sense for c++ - classes are not first class objects (like in e.g. java).
A (static|anything) constructor implies something is constructed - and c++ classes aren't constructed, they just are.
You can easily achieve the same effect though:
//.h
struct Foo {
static std::vector<std::string> strings;
};
//.cpp
std::vector<std::string> Foo::strings(createStrings());
IMO there's just no need for one more syntactic way of doing this.
In which translation unit would the static objects be placed?
Once you account for the fact that statics have to be placed in one (and only one) TU, it's then not "very difficult" to go the rest of the way, and assign values to them in a function:
// .h
class sample
{
public:
static int some_integer;
static std::vector<std::string> strings;
};
//.cpp
// we'd need this anyway
int sample::some_integer;
std::vector<std::string> sample::strings;
// add this for complex setup
struct sample_init {
sample_init() {
sample::some_integer = 100;
sample::strings.push_back("stack");
sample::strings.push_back("overflow");
}
} x;
If you really want the code for sample_init to appear in the definition of class sample, then you could even put it there as a nested class. You just have to define the instance of it in the same place you define the statics (and after they've been initialized via their default constructors, otherwise of course you can't push_back anything).
C# was invented 15-20 years after C++ and has a completely different build model. It's not all that surprising that it offers different features, and that some things are less simple in C++ than in C#.
C++0x adds a features to make it easier to initialize vectors with some data, called "initializer lists"
You could get by with putting your "static" members in their own class with their own constructor that performs their initialization:
class StaticData
{
int some_integer;
std::vector<std::string> strings;
public:
StaticData()
{
some_integer = 100;
strings.push_back("stack");
strings.push_back("overflow");
}
}
class sample
{
static StaticData data;
public:
sample()
{
}
};
Your static data member is guaranteed to be initialized before you first try to access it. (Probably before main but not necessarily)
Static implies a function that is disassociated with an object. Since only objects are constructed, it is not apparent why a static constructor would have any benefit.
You can always hold an object in a static scope which has been constructed in a static block, but the constructor you would use would still be declared as non-static. There's no rule that indicates you can't call a non-static method from a static scope.
Finally, C++ / C defines the start of a program to be when the main function is entered. Static blocks are called prior to the entry of the main function as part of setting up the "environment" of the evaluated code. If your environment dictates full control over the set-up and tear-down, then it's easy to argue that it's not really some environmental fixture as much as an inherit procedural component of the program. I know that the last bit is sort of code-philosophy (and that it's rationale could be interpreted differently), but one shouldn't put critical code "before" the official start of an executable's handing off "full control" to the code written by the programmer.

Imitate a static constructor in C++

This a question related to the initialization of objects in C++.
I have a group of classes (not instances), inheriting from a common base class, and I need them to register info about themselves in a container (specifically a map) when the program starts.
The problem is that I need it to be dynamic. The container is defined in an independent project, different from the classes. I would prefer to avoid making multiple hard-coded versions of the library, one for each set of classes in each program that uses it.
I thought about having a static instance of a special class in each of these subclasses, that would make the registration in its constructor. However, I have found no way to guarantee that the container will be constructed before the construction of these objects.
I should also note that the information in the container about the subclasses should be available before any instance of these subclasses is created.
Is there a way to do this, or imitate a static constructor in C++ in general?
You are describing different problems all at once. On the particular issue of having some sort of static initialization, a simple approach is creating a fake class that will perform the registration. Then each one of the different classes could have a static const X member, the member will have to be defined in a translation unit, and the definition will trigger the instantiation of the instance and the registration of the class.
This does not tackle the hard problem, which is the initailization order fiasco. The language does not provide any guarantee on the order of initialization of objects in different translation units. That is, if you compile three translation units with such classes, there is no guarantee on the relative order of execution of the fake member. That is also applied to the library: there is no guarantee that the container in which you want to register your classes has been initialized, if such container is a global/static member attribute.
If you have access to the code, you can modify the container code to use static local variables, and that will be a step forward as to ensure the order of initialization. As a sketch of a possible solution:
// registry lib
class registry { // basically a singleton
public:
static registry& instance() { // ensures initialization in the first call
static registry inst;
return inst;
}
// rest of the code
private:
registry(); // disable other code from constructing elements of this type
};
// register.h
struct register {
template <typename T>
register( std::string name ) {
registry::instance().register( name, T (*factory)() ); // or whatever you need to register
}
};
// a.h
class a {
public:
static a* factory();
private:
static const register r;
};
// a.cpp
const register a::r( "class a", a::factory );
// b.h/b.cpp similar to a.h/a.cpp
Now in this case there is no definite order among the registration of the a and b classes, but that might not be an issue. On the other hand, by using a local static variable in the registry::instance function the initialization of the singleton is guaranteed to be performed before any call to the registry::register methods (as part of the first call to the instance method).
If you cannot make that change you are basically out of luck and you cannot guarantee that the registry will be instantiated before the other static member attributes (or globals) in other translation units. If that is the case, then you will have to postpone the registration of the class to the first instantiation, and add code to the constructor of each class to be registered that ensures that the class is registered before actual construction of the object.
This might or not be a solution, depending on whether other code creates objects of the type or not. In the particular case of factory functions (first one that came to mind), if nothing else is allowed to create objects of types a or b... then piggy backing registration on constructor calls will not be a solution either.
This is a candidate for the Singleton pattern. Basically, you want the container to be instantiated when the first instance of a subclass is instantiated. This can be facilitated by checking if the singleton pointer is NULL in the base-class constructor, and if so, then instantiate the container.
One idea is to pass a registration functor to the classes. Each descendant would execute the function to register. This functor could be passed in the constructor.
Example:
struct Registration_Interface
{
virtual void operator() (const std::string& component_name) = 0;
};
struct Base
{
};
struct Child1
: public Base
{
Child(Registration_Interface& registration_ftor)
{
//...
registration_ftor("Child1");
}
};
See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14
One option is to construct the container lazily, when the first thing is added to it:
void AddToContainer(...) {
// Will be initialized the first time this function is called.
static Container* c = new Container();
c->Add(...);
}
The only way to "imitate" a static constructor is to explicitly call a function to perform your static initialization. There is no other way to run code pre-main just by linking in a module.
You might use an "initialise on first use" pattern, and then instantiate a dummy static instance to ensure initialisation as early as possible.
class cExample
{
public :
cExample() ;
// Static functions here
private :
static bool static_init ;
// other static members here
}
cExample::static init = false ;
cExample::cExample()
{
// Static initialisation on first use
if( !static_init )
{
// initialise static members
}
// Instance initialisation here (if needed)
}
// Dummy instance to force initialisation before main() (if necessary)
static cExample force_init ;
It is against OOP paradigm, but how about having your static members form a linked list guided by 2 global variables? You could do something like that:
ClassRegistrator *head = nullptr;
ClassRegistrator *tail = nullptr;
struct ClassRegistrator {
// ... Data that you need
ClassRegistrator *next;
ClassRegistrator(classData ...) {
if (!head)
head = tail = this;
else {
tail->next = this;
tail = this;
}
// ... Do other stuff that you need for registration
}
};
// The class you want to register
class MyClass {
static ClassRegistrator registrator;
}
ClassRegistrator MyClass::registrator(...); // Call the constructor
I believe the global variables, as they don't need have a constructor, but are just pure data, are guaranteed to be already initialised when you begin the execution of your code.
Obviously this is not thread-safe, etc, but should make your job done.

Initialization order with constructors in C++

By instantiating an object in C++ with the following class I get a segmentation fault or aborts, depending on the order declaring member variables. E. g. putting mMemberVar and mAnotherMemberVar after mAnotherCountVar results in a segfault. From this listing I removed a std::ofstream from the member variables, which caused the segmentation fault independent of its position.
I think the order is not directly the problem, but what do you think could the reason be? This class is part of a huge project, but this in this class is the place, where the error appeared the first time.
class COneClass : public IInterface
{
public:
COneClass();
virtual ~COneClass();
static const unsigned int sStaticVar;
static const unsigned int sAnotherStaticVar;
private:
COneClass();
COneClass(const COneClass& );
COneClass& operator=(const COneClass& );
int mMemberVar;
int mAnotherMemberVar;
bool mIsActive;
bool mBoolMemberVar;
bool mAnotherBoolMemberVar;
unsigned int mCountVar;
unsigned int mAnotherCountVar;
};
COneClass::COneClass() :
mMemberVar(0),
mAnotherMemberVar(0),
mIsActive(false),
mBoolMemberVar(false),
mAnotherBoolMemberVar(false),
mCountVar(sStaticVar),
mAnotherCountVar(sAnotherStaticVar)
{
}
the class members are initinised by the order they are declared. the order in the init list does not matter. In your case it's this order:
mMemberVar -> mAnotherMemberVar -> mIsActive -> mBoolMemberVar -> mAnotherBoolMemberVar -> mCountVar -> mAnotherCountVar;
Perhaps it is a case of the "static initialization order fiasco", http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.16, as a result of initializing mCountVar and mAnotherCountVar with static members?
You could init to zero in the list and then assign in the body of the constructor.
Could be "static initialization order fiasco" judging by the fact that you have public static variables and a private constructor (speaking of which how can you have a public and private definition of the constructor???). These signs indicate the possibility that there is a dependency with other classes here.
The members’ constructors are called before the body of the containing class’ own constructor
is executed. The constructors are called in the order in which they are declared in the class rather
than the order in which they appear in the initializer list.
To avoid confusion, it is best to specify the initializers in declaration order.
The member destructors are called in the reverse order of construction every thing work properly
class MyClass//**1: mem-init**
{
private:
long number;
bool on;
public:
MyClass(long n, bool ison) : number(n), on(ison) {}
};
MyClass(long n, bool ison) //2 initialization within constructor's body
{
number = n;
on = ison;
}
There is no substantial difference between the two forms in the case of MyClass's constructor. This is due to the way mem-initialization lists are processed by the compiler. The compiler scans the mem-initialization list and inserts the initialization code into the constructor's body before any user-written code. Thus, the constructor in the first example is expanded by the compiler into the constructor in the second example. Nonetheless, the choice between using a mem-initialization list and initialization inside the constructor's body is significant in the following four cases:
Initialization of const members
Initialization of reference members
Passing arguments to a constructor of a base class or an embedded object
Initialization of member objects
I think the whole class is not directly the problem. Can you produce a minimal code that crashes just by using this class? It seems to me that the problem is somewhere else in your code base.
However, you may add a bool Invariant() const; function to that class and call it (only in debug builds) with assert(Invariant()); at the end of your constructor and on entering and exiting all your public functions. This might help you to "crash early, crash often" and hence point you to some of the problematic code.
This doesn't look like your real code. But be aware in your real code, that class members are constructed in the order they are defined in the class, REGARDLESS of the order of the initializer list in the constructor. Given that you mention changing the order of the members in the class affects the problem, this might be what's wrong. For example, your code might do something like this:
class MyClass {
public:
const int member1;
const int member2;
MyClass() {
: member2(0),
: member1(member2) // ERROR: this runs first because member1 is defined first
// member2 not yet constructed; assigns undefined value to member1
{}
};
There's nothing in the code you've posted which is in any way abnormal. Either something in the IInterface constructor is failing, or something else entirely is going wrong. Perhaps you've a buffer overflow somewhere which is reading the data you've changing the structural order of.