How to access class member and methods from static method(signal handler) - c++

I have one problem. I am writing my program on C++ language. I have one problem. I need to set signal handler for my process. As the signal is related with the process on system level I have faced the problem.
My program consists of several classes. They are connected together. But it doesn't matter in this case.
The problem is that I need access to member and methods of the class from my signal handler. For instance, I have a class named Foo at it has some members and methods.
So from my handler I need to call its function and change members.
I understand that compiler should know that this class instances will exist during all program execution.
I have tried to set static member class Foo instance in another class , but this didn't solve the problem.
I have no idea what is the correct approach for doing this. Please explain how to correctly implement signal handling in such case.
Here is an example of my code:
class MyContainer
{
private:
std::vector<Foo> container;
public:
int removeFromContainer(Foo* aFoo) {
// DO some stuff
return RESULT_CODE;
}
int addToContainer(Foo* aFoo) {
// DO some stuff
return RESULT_CODE;
}
};
Here is my Main class
class MainClass
{
private:
int member;
public:
void mainLoop(char* args) {
signal(SIGCHLD, &signalHandler);
}
};
Here is my function for signal handling
void static signalHandler_child(int p)
{
this->myContainerInstance->addToContainer(new Foo);
}

A static method is not so different from a global function. If you need to access instance members of a class, your signal handler should take an instance pointer/reference as argument.
Something like this
class Foo
{
private:
int member;
public:
static int Handler(Foo* aFoo) { return aFoo->member; }
};

Related

C++ - Identify derived class from base class pointer at runtime

I'm experimenting with state machines and the one that I'm trying to implement uses function pointers to represent states
typedef void (*State)(Signal const&)
class StateMachine
{
public:
void exampleState(Signal const&);
private:
State m_currentState;
}
Basically, I want to derive a separate class for each signal and in each state function the state machine must be able to determine which kind of signal has been received and execute the corresponding code. A solution that I came up with is something like
class Signal {};
class MySignal: public Signal {};
void StateMachine::exampleState(Signal const& signal){
if (typeid(signal) == typeid(MySignal)){
//code here
}
// other cases...
}
First of all I'm not sure that using typeid this way is good practice. Also, this only works if Signal has at least one virtual function.
Another solution would be to define a sort of type flag like an enum, and pass the corresponding one in the derived signal constructor
enum signalType{
mySignalType
//other types
}
class Signal {
public:
Signal(signalType sig_type):m_type(sig_type){};
const signalType m_type;
};
class MySignal: public Signal {
public:
MySignal():Signal(mySignalType){};
};
void StateMachine::exampleState(Signal const& signal){
switch (signal.m_type){
case mySignalType:
//code here
break;
// other cases...
}
}
althoug this requires the enum to be extended each time a new signal class is written.
Is there a more elegant way of achieving this? Or maybe another technique that avoids this check at all? I remember having this problem in other scenarios as well, that's why the question in the title is more general than the example above.
What you want to achieve can be done through polymorphism.
Declare a method (or abstract method) in Signal, and implement it in MySignal:
class Signal {
public:
virtual void my_method() const = 0;
};
class MySignal: public Signal {
public:
void my_method() const override {
// do something
}
};
then call your method in exampleState, this will call the implemented method:
void StateMachine::exampleState(Signal const& signal){
signal.my_method();
}
Use dynamic_cast instead of typeid:
class Signal {
public:
virtual ~Signal() {}
};
class MySignal: public Signal {};
void StateMachine::exampleState(Signal const& signal){
if (dynamic_cast<MySignal const *>(&signal)){
//code here
}
// other cases...
}

Namespace Functions within Class alternatives?

I'd like to be able to group similar functions in a class into a group so I don't need to append each name with what it's about.
I've seen this question which says that you can't have namespaces within classes. I've also seen this question which proposes using strongly typed enums. The problem here though, is that I'm not sure whether or not these enums can actually accomodate functions?
The problem contextualised:
class Semaphore
{
public:
void Set(bool State){Semaphore = State;}
bool Get(){return Semaphore;}
void Wait()
{
while (Semaphore)
{
//Wait until the node becomes available.
}
return;
}
private:
bool Semaphore = 0; //Don't operate on the same target simultaneously.
};
class Node : Semaphore
{
public:
unsigned long IP = 0; //IP should be stored in network order.
bool IsNeighbour = 0; //Single hop.
std::vector<int> OpenPorts;
//Rest of code...
};
Currently, NodeClass.Get() is how I can get the semaphore. However this introduces confusion as to what Get() actually gets. I'd like to have something akin to NodeClass.Semaphore::Get(). Otherwise I'd have to have the functions as SemaphoreSet(), SemaphoreGet(), and SemaphoreWait(), which isn't too well organised or nice looking.
I had thought of just having the Semaphore class on it's own, and instantiating it within the other classes, but if I could stick with the inheritance approach, that would be nicer.
So essentially, is it possible to access inherited methods like InheritedClass.Group::Function()?
If you really want to do this, you could force the user to call with the base class name by deleteing the member function in the subclass:
class Base {
public:
void Set(bool) { }
};
class Derived : public Base {
public:
void Set(bool) = delete;
};
int main() {
Derived d;
// d.Set(true); // compiler error
d.Base::Set(true);
}
However, if the semantics of calling Set on the subclass are significantly different than what you'd expect them to be when calling Set on the base class, you should probably use a data member and name a member function accordingly as you've described:
class Base {
public:
void Set(bool) { }
};
class Derived {
public:
void SetBase(bool b) {
b_.Set(b);
}
private:
Base b_;
};
int main() {
Derived d;
d.SetBase(true);
}

Use a derived class automatically

I work on TTY communication with different protocols. I started to implement some code in C++ with classes. A parent class contains some basic functions (write, read...) with some virtual functions. Each protocol is a child class with specific functions. Currently in my application, I'm using directly my child classes, but I want to change the protocol dynamically.
Is it possible in this case to use the parent class as an automatic selector for the child class to choose? And to still use the parent after this selection?
For example (simplified):
class Parent
{
void Write();
void Read();
void AutomaticProtocolSelector();//depending on the response of the device
virtual void function1();
virtual void function2();
};
class protocol1 : public Parent
{
void function1();
};
class protocol2 : public Parent
{
void function2();
};
int main(int argc, char const *argv[])
{
Parent *p;
p->AutomaticProtocolSelector();//let's say protocol1 is selected
p->function1(); //execute the function1 in the child class
...
}
I already read some posts about derived classes and the use of dynamic_cats and static_cast, but it's not exactly what I'm looking for. I'll use this if it's not possible in the way I think.
You seem to be in a kind of bootstrapping problem. You want to use a pointer to Parent to create an implementation of the Parent class. In your program, you are dereferencing a pointer that has not been initialized.
int main(int argc, char const *argv[])
{
Parent *p; // !! Not initialized
p->AutomaticProtocolSelector(); // The application should crash here
p->function1();
// ...
}
Preferably initialize your pointers as nullptr, that might make it more obvious that something fishy is going on.
To let the Parent class provide an implementation of itself, you need a static factory method.
class Parent
{
public:
static std::unique_ptr<Parent> createParent();
void Write();
void Read();
virtual void function1();
virtual void function2();
};
This can then be used in your application as follows:
int main()
{
auto p = Parent::createParent();
p->function1();
p->function2();
// ...
}
However, this also means that in your implementation of Parent, you need to know about some or all possible child classes. This feels a bit backwards, you generally don't want your parent classes to know about their child classes.
As Alexandre Thouvenin also advised, it might be best to move the construction of a child class into a separate factory class.
class ParentFactory
{
public:
ParentFactory() = default;
std::unique_ptr<Parent> createParent() const;
};
In the implementation of the createParent method, you then create an instance of one of the child classes.
Then in your application code, create a factory and use it to get hold of an implementation of the Parent class.
int main()
{
ParentFactory factory;
auto p = factory.createParent();
p->function1();
p->function2();
// ...
}
Note: I used some C++11 features, I hope you don't mind.

C++ calling objects from another class

I asked this question here: C++ Method chaining with classes
In essesance, what I am trying to do is call a Constructor/Method from another class using Method chaining. Let's say I have 2 classes:
class Signal {
public:
Signal() { } // constructor
Signal& ParseSignal() {
// In this method I want to call
// the constructor "Parse()"
}
protected:
std::vector<double> data;
};
And I have another class called Parse:
class Parse {
public:
Parse() {
// This is the implementation
// I need to access the "data" contained in class "Signal
};
My main objective would be to do the following in main:
Signal s = Signal().ParseSignal();
This would then accept the signal, and, Parse this.
Someone suggested that I should use CRTP however, due to the fact that the base class (in this case Signal) has to have a template<> argument, this is not possible due to other classes inheriting.
Is there another solution to this problem?
EDIT:
I have tried the following, however, it looks like a dirty implementation and I cannot access the member variable:
class Parser {
public:
Parser() {
parse();
}
void parse() {
cout << "YES";
}
};
class Signal {
public:
friend class Parser;
Signal() { val = 0;}
Signal& Parse() {
Parser::Parser();
return *(this);
}
protected:
int val;
};
You implicitly cannot and should not do what you appear to be trying to do, which is to call the constructor of a class without constructing an instance of the class.
If you want the behavior of Parser in Signal, then you have at least three options: 1. Inherit Parser, 2. Add a Parser member, 3. Create a "Parseable" interface-class which Parser can take as an argument.
class Parser {
public:
class Interface {
public:
std::vector<double> m_data;
};
Parser(Interface& interface) {
parse(interface);
}
};
class SignalInheriting : public Parser::Interface {
public:
SignalInheriting() {
Parser p(*this); // can take the Parser::Interface view of this object.
}
};
class SignalMember {
Parser::Interface m_parserIface;
public:
SignalMember() : m_parserIface() {
}
};
Doing heavy lifting in constructors like this is great for obfuscated or dog-show code, but is terrible for production systems that require any kind of maintenance.
But if you're fine with having to diagnose problems in code that works hands-free like this at 3am on a Saturday when you're hung over - then go for it.
A major factor to which pattern you should choose is how long the parse-related data is going to persist vs how long the Signal objects are going to persist.
Conversely, if the Signal object is little more than a specialization of the "Parse" API, then just inherit Parse and be done with.
The simplest way to do what you are trying to do would be something like this:
class Parse {
public:
Parse(std::vector<double> &data) {
// do stuff
}
};
class Signal {
public:
Signal() { } // constructor
Signal& ParseSignal() {
Parse parser(data);
return *this;
}
protected:
std::vector<double> data;
};
However I suggest that you take a look at the Visitor Pattern for a more generic solution.
Or at the very least don't do the work in the Parse constructor, do it in some method instead.

Enforce static method overloading in child class in C++

I have something like this:
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template <typename T>
int Produce()
{
return T::Lolz();
}
and
Produce<Base>();
Produce<Child>();
both return 0, which is of course correct, but unwanted. Is there anyway to enforce the explicit declaration of the Lolz() method in the second class, or maybe throwing an compile-time error when using Produce<Child>()?
Or is it bad OO design and I should do something completely different?
EDIT:
What I am basically trying to do, is to make something like this work:
Manager manager;
manager.RegisterProducer(&Woot::Produce, "Woot");
manager.RegisterProducer(&Goop::Produce, "Goop");
Object obj = manager.Produce("Woot");
or, more generally, an external abstract factory that doesn't know the types of objects it is producing, so that new types can be added without writing more code.
There are two ways to avoid it. Actually, it depends on what you want to say.
(1) Making Produce() as an interface of Base class.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
friend int Produce<Base>();
protected:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // error :'Base::Lolz' : cannot access protected member declared in class 'Base'
}
(2) Using template specialization.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template<>
int Produce<Child>()
{
throw std::bad_exception("oops!");
return 0;
}
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // it will throw an exception!
}
There is no way to override a static method in a subclass, you can only hide it. Nor is there anything analogous to an abstract method that would force a subclass to provide a definition. If you really need different behaviour in different subclasses, then you should make Lolz() an instance method and override it as normal.
I suspect that you are treading close to a design problem here. One of the principals of object-oriented design is the substitution principal. It basically says that if B is a subclass of A, then it must be valid to use a B wherever you could use an A.
C++ doesn't support virtual static functions. Think about what the vtable would have to look like to support that and you'll realize its a no-go.
or maybe throwing a compile-time error when using Produce<Child>()
The modern-day solution for this is to use delete:
class Child : public Base
{
public:
int nothing;
static int Lolz() = delete;
};
It helps avoid a lot of boilerplate and express your intentions clearly.
As far as I understand your question, you want to disable static method from the parent class. You can do something like this in the derived class:
class Child : public Base
{
public:
int nothing;
private:
using Base::Lolz;
};
Now Child::Lolz becomes private.
But, of course, it's much better to fix the design :)