Accessing a variable from an unrelated function in C++ - c++

I want to access a variable of one class into another class, and set it to some value, e.g. like in code here, i wanna set the some_flag to true in the secondClassFunction(). Is it possible? If yes, how to do it?
Constraints due to system architecture:
The two classes are not inheritable.
The two classes are not related either.
The function signatures of secondClassFunction()cannot be changed.
Here's the code snippet:-
#include <iostream>
using namespace std;
class FirstClass{
bool some_flag;
public:
void setFlag(bool flag);
bool getFlag();
};
FirstClass::FirstClass(){
some_flag(false);
}
class SecondClass{
public:
void secondClassFunction();
}
SecondClass::secondClassFunction(){
// do something here.
// I want to access some_flag using SecondClass object.
// how to do this?
}
int main() {
SecondClass secObj;
secObj.secondClassFunction();
return 0;
}
Will wrapper classes help? If yes, how?
EDIT:-
Constraint 4. Cannot make the classes friend functions.
Constraint 5. Cannot globalize the flag variable.
Details:-
The flag is set in a function which is a member of FirstClass.
I wish to reset this flag in a function which is member of the SecondClass.
The two classes are not related, inheritable, and their access specifiers cannot be changed, due to constraints of the system architecture.
The flag is like a semaphore, it's used by multiple tasks, to denote the status of an activity, such as, whether the processor has received a certain command from a mobile app or not.

It seems that you do not care about instance of the FirstClass. So the following approach will work for you:
void SecondClass::secondClassFunction()
{
// Create local instance of the object to change
FirstClass first;
first.setFlag(true);
}
But it makes no sense at all. You need to know which object to modify. I'd suggest three options:
make instance of FirstClass static, global or singleton and modify it
make some_flag and its setter static
set instance of the FirstClass to context before calling SecondClass::secondClassFunction()
Third option explained:
class FirstClass; // Forward declaration
class SecondClass
{
...
FirstClass* firstClassInstance;
...
void setFirstClassInstanceToModify(FirstClass* first)
{
firstClassInstance = first;
}
...
};
void SecondClass::secondClassFunction()
{
firstClassInstance->setFlag(true);
}
And call it like this
FirstClass first;
...
SecondClass second;
...
second.setFirstClassInstanceToModify(&first);
second.secondClassFunction();
But make sure to have proper and valid instance before calling secondClassFunction

Related

Is it possible to override member access operators to detect when any member variable is modified?

Say I have:
struct foo{
int bar;
int baz;
...
bool flag;
}
Can an access operator -> or . be overridden to detect if bar or any other member variable is modified ?
EDIT:
The purpose is if I have many member variables and any of them is changed, I have a quick way of setting a flag, instead of using setters to encapsulate all the variables, making the code verbose.
Your approach is flawed because even if you override access operators you will not catch pointers writing the actual memory.
If most of the variables have the same type you can use an enum for flags and a single function to set or get a specific variable.
For example:
private:
int bar;
int baz;
public:
enum IntVariables { varBar, varBaz };
bool flag;
void setVariable(int varId, int value) {
flag = true;
if (varId == varBar)
bar = value;
else if (varId == varBaz)
baz = value;
}
I considered the following approach:
Just use a wrapper class that can have any data type, but implement all operations. In this same wrapper class override operators, and use the wrapper class in other class that require any modifications of member variables to be detected.
template <class T>
class wrapper {
private:
T var;
... .. ...
public:
T doSomethingToVar(T arg);
... .. ...
//Wherever the variable is modified send out a notification to whomever needs to detect the changes.
};
Pros:
When declaring variables in whichever class needs to detect modification of variables, it is easy to declare using the wrapper, without much additional code.
To ensure modifications are detected, need to implement functions / getters / setters / overload operators to detect modifications. This is tricky, and requires some thought.
Cons:
Tricky to implement a general purpose wrapper that can detect all modifications, since complex types can have functions that modify themselves in ways one is not aware of.
Notes:
How to ensure that every method of a class calls some other method first?
This answer is a work in progress, and I think it may be useful to others and maybe just cool to know about eventually, so open to comments. Will keep updating.
Update:
While writing out the above answer, I considered a different approach, of shifting responsibility onto the member variable classes:
class DetectChanges{
void onDetectChanges(){
//This function should be called by all implementing classes when the class has changes.
}
Can make it a design choice that all member variables inherit from DetectChanges.
The above two approaches are what I'm considering now. Not a solution yet, but thought I would put it out for comments and see if eventually we can figure something out.
}

C++ Force Compile-Time Error Based on which Constructor is Called

In my C++ class, I want to prevent certain member functions from being able to be called depending on which constructor is used to create the object, and cause a compile-time error if this is attempted.
A bit of context:
I have an existing widely-used class in my project that is used to read/write to a database. Sometimes when I create an instance of this class, I only want to read from the database, and because of this, I want to create a new constructor which is a "read-only" constructor that prevents all functions that write to the database from doing anything. (My reason for doing this is because I want to "lock out" the row from the database being accessed if the object is going to write to it, but not do this if the object is only reading from the database.)
Of course, this is not very difficult to accomplish to prevent a member function from doing anything during run-time based on which constructor is used. For example:
class DatabaseInterface
{
private:
bool readOnly;
public:
// Constructor #1
// This constructor allows read only from database
DatabaseInterface(int x)
{
readOnly = true;
// Do something
}
// Constructor #2
// This constructor allows read/write to database
DatabaseInterface(int x, bool y)
{
readOnly = false;
// Do something
}
void UpdateDatabase()
{
if (readOnly) return;
// Update Database
}
};
With this class, you can do this:
DatabaseInterface A(5);
DatabaseInterface B(5,true);
A.UpdateDatabase(); // Does nothing
B.UpdateDatabase(); // Updates database
But is there a way to modify this class such that A.UpdateDatabase() above would cause a compile-time error?
My thinking is that (since all instances of my class currently use a constructor with one argument) if I can force a compile-time error for this, then I can ensure that all instances of the class will use the correct constructor, because it will not even compile if a "writing" function is attempted to be used on an object that was created with a "read-only" constructor.
I am wondering if this is possible because note that the value of the second argument in the constructor doesn't matter, as long as it is a bool type.
If you are willing to make the class a template then you can use tags to make a read-only DatabaseInterface or a read-write DatabaseInterface. That would look like
struct read_only_t{};
struct read_write_t{};
template<typename T>
class DatabaseInterface
{
public:
DatabaseInterface(int x)
{
// Do something
}
void UpdateDatabase()
{
static_assert(!std::is_same_v<T, read_only_t>, "DatabaseInterface is in read only mode");
// Update Database
}
};
And now you get a nice compiler error if you try to call UpdateDatabase on a DatabaseInterface<read_only_t>
Yes, you can make it fail at compile time provided you are willing to template your DatabaseInterface class.
You'd need to add a template argument of type bool, for example, and then specialize the UpdateDatabase() function only for template parameter value of <true>. When you try to call the UpdateDatabase() function on an object where the parameter is <false>, the compiler will complain that the function is declared, but not defined.
You can use inheritance for this:
class ReadOnlyDBI {
public:
void readData();
virtual ~ReadOnlyDBI();
};
class ReadWriteDBI : public ReadOnlyDBI {
public:
void writeData();
};
void someFunctionReadingData( ReadOnlyDBI &dbi )
{
dbi.readData(); // fine
dbi.writeData(); // error, this function can only read
}
void foo()
{
ReadWriteDBI rwd;
rwd.readData(); // fine to read from it
someFunctionReadingData( rwd ); // we can pass it to a func that reads
rwd.writeData(); // we can write
}
otherwise you will have to write someFunctionReadingData as template as well.

A singleton-like manager class, better design?

I'm making a game engine and I'm using libraries for various tasks. For example, I use FreeType which needs to be initialized, get the manager and after I don't use it I have to de-initialize it. Of course, it can only be initialized once and can only be de-initialized if it has been initialized.
What I came up with (just an example, not "real" code [but could be valid C++ code]):
class FreeTypeManager
{
private:
FreeTypeManager() {} // Can't be instantiated
static bool initialized;
static TF_Module * module; // I know, I have to declare this in a separate .cpp file and I do
public:
static void Initialize()
{
if (initialized) return;
initialized = true;
FT_Initialize();
FT_CreateModule(module);
}
static void Deinitialize()
{
if (!initialized) return;
initialized = false;
FT_DestroyModule(module);
FT_Deinit();
}
};
And for every manager I create (FreeType, AudioManager, EngineCore, DisplayManager) it's pretty much the same: no instances, just static stuff. I can see this could be a bad design practice to rewrite this skeleton every time. Maybe there's a better solution.
Would it be good to use singletons instead? Or is there a pattern suiting for my problem?
If you still want the singleton approach (which kind of makes sense for manager-type objects), then why not make it a proper singleton, and have a static get function that, if needed, creates the manager object, and have the managers (private) constructor handle the initialization and handle the deinitialization in the destructor (though manager-type objects typically have a lifetime of the whole program, so the destructor will only be called on program exit).
Something like
class FreeTypeManager
{
public:
static FreeTypeManager& get()
{
static FreeTypeManager manager;
return manager;
}
// Other public functions needed by the manager, to load fonts etc.
// Of course non-static
~FreeTypeManager()
{
// Whatever cleanup is needed
}
private:
FreeTypeManager()
{
// Whatever initialization is needed
}
// Whatever private functions and variables are needed
};
If you don't want a singleton, and only have static function in the class, you might as well use a namespace instead. For variables, put them in an anonymous namespace in the implementation (source) file. Or use an opaque structure pointer for the data (a variant of the pimpl idiom).
There's another solution, which isn't exactly singleton pattern, but very related.
class FreeTypeManager
{
public:
FreeTypeManager();
~FreeTypeManager();
};
class SomeOtherClass
{
public:
SomeOtherClass(FreeTypeManager &m) : m(m) {}
private:
FreeTypeManager &m;
};
int main() {
FreeTypeManager m;
...
SomeOtherClass c(m);
}
The solution is to keep it ordinary c++ class, but then just instantiate it at the beginning of main(). This moves initialisation/destruction to a little different place. You'll want to pass references to FreeTypeManager to every class that wants to use it via constructor parameter.
Note that it is important that you use main() instead of some other function; otherwise you get scoping problems which require some thinking how to handle..

How do I call local function from a static function?

#ifndef DATACENTER_H_
#define DATACENTER_H_
#include <map>
#include <list>
#include <string>
#include "LiLo/SoundInfo.h"
#include "MutexCondition.h"
#include "UserInfo.h"
using namespace std;
class DataCenter : MutexCondition{
private:
map<long long, list<SoundInfo *> > m_soundListMap;
void add(long long deviceId, SoundInfo* soundInfo);
public:
DataCenter();
virtual ~DataCenter();
static void addSoundInfo(long long deviceId, SoundInfo *soundInfo);
};
#endif /* DATACENTER_H_ */
DataCenter.cpp file
#include "DataCenter.h"
DataCenter::DataCenter() {
// TODO Auto-generated constructor stub
}
DataCenter::~DataCenter() {
// TODO Auto-generated destructor stub
}
void DataCenter::addSoundInfo(long long deviceId, SoundInfo *soundInfo){
add(deviceId, soundInfo);
}
void DataCenter::add(long long deviceId, SoundInfo *soundInfo){
list<SoundInfo*>& info_list = m_soundListMap[55];
}
I am trying to access the function call addSoundInfo from other classes so I have set this as static. Since the m_soundListMap is not a static so I think I need another function to access to the local data structure.
Inside of the static function, I call add function to add SoundInfo to the list. However, I am getting an error in the static function and it says "Can not call member function .... without object".
How do I fix this problem? Thanks in advance..
If you want to access addSoundInfo from other classes, you need to make it public, or make those other classes friends of DataCenter. static has nothing to with access control.
A static function is not bound to an instance of the class it belongs to, and thus can not access members of that class (it also can not call member-functions). If you really want to access members from a static function, you have to pass an instance of the class as argument the the static function explicitly.
If you struggle with such basic concepts, you should read a good book.
I suppose you mean you don't want to make void add() public and still you want to access it from some classes. It is nothing wrong with that and you can do it this way:
class A
{
private:
void DoPrivateStuf() {}
friend class B; // now B can access A private stuf
};
class B
{
// can have any modifier: public, private, protected depending on your needs
public:
void DoPrivateStufToA( A& a )
{
a.DoPrivateStuf();
}
};
The code seems hopelessly jumbled, but technically you just need to remove the word static. Then you can call dc.addSoundInfo( id, pSoundInfo ) where dc is a DataCenter object.
Cheers & hth.,
static is a way to instruct the compiler "the following function is not manipulating instance variable, only things that are global to all the instances of this class". You use that when you need to keep your constructor private for some reason, or have a function that does instances management (registration, etc.)
When you intend to have only one instance of a given class (e.g. because it is a resource manager), you usually prefer to follow the singleton pattern: a static getInstance() method that return the only instance of that class and create it if needed, then you keep your other methods regular methods and your state instance members.
As others have said, making addSoundInfo() public is enough for it to be available from other class. I'll just add some points about C++'s keyword static. Basically, it has many meanings depending on where is it used. When one uses it for functions, there are two meanings:
static class function: a function that is tied to a class, not any specific object. In this sense, it is similar to namespace concept - using the scope :: operator to access the function.
static function: The function has internal linkage, which means it is only visible in current translation unit (current source file). It is handy for utility functions.
In your case, the answer to your question will technically be something like this:
In the header file:
class DataCenter
{
static void addSoundInfo(DataCenter& dc, long long deviceId, SoundInfo *soundInfo);
}
In the source file:
void DataCenter::addSoundInfo(DataCenter& dc, long long deviceId, SoundInfo *soundInfo)
{
dc.add(deviceId, soundInfo);
}
But it is probably not what you want.

Access class functions from another thead?

I have a function in my class that creates a thread and gives it arguments to call a function which is part of that class but since thread procs must be static, I can't access any of the class's members. How can this be done without using a bunch of static members in the cpp file to temporarily give the data to be manipulated, this seems slow.
Heres an example of what I mean:
in cpp file:
void myclass::SetNumber(int number)
{
numberfromclass = number;
}
void ThreadProc(void *arg)
{
//Can't do this
myclass::SetNumber((int)arg);
}
I can't do that since SetNumber would have to be static, but I instance my class a lot so that won't work.
What can I do?
Thanks
Usually you specify the address of the object of myclass as arg type and cast it inside the ThreadProc. But then you'll be blocked on how passing the int argument.
void ThreadProc(void *arg)
{
myclass* obj = reinterpret_cast<myclass*>(arg);
//Can't do this
obj->SetNumber(???);
}
As you said this is maybe not only a bit slow but it also clutters the code. I would suggest to use boost::bind for argument binding and to create the threads in an os independent way (for your own source at least) you could use boost::thread. Then no need for static methods for your threads.
Now in the C++0x standard, here a small tutorial
I would suggest you to make a friendly class with a static method for this purpose. It looks much cleaner. Eg:-
class FriendClass
{
public:
static void staticPublicFunc(void* );
};
Now befriend the above class in your main class ...
class MyClass
{
friend void FriendClass::staticPublicFunc(void*);
};
This should enable you to set the friend-function as the thread-function and access the class per instance in each thread. Make sure to synchronize your access to data visible across threads.