In my OMNeT code, I want an Egg class to inherit from Chicken. Having said that, in my Chicken class I want to get a pointer to the Egg and work with it.
The following code crashes when Qtenvironment starts, saying Simulation terminated with exit code: 139
ChickenEggNetwork.ned
package chickenegg.simulations;
import chickenegg.Chicken;
import chickenegg.Egg;
network ChickenEggNetwork {
submodules:
chicken: Chicken;
egg: Egg;
}
Chicken.ned
package chickenegg;
simple Chicken {
@class(Chicken);
}
Chicken.h
#ifndef CHICKEN_H_
#define CHICKEN_H_
#include <omnetpp.h>
class Egg; // forward declaration
class Chicken : public omnetpp::cSimpleModule {
private:
void initialize(void);
Egg* egg; // Get a pointer to Egg class
};
#endif /* CHICKEN_H_ */
Chicken.cc
#include "Chicken.h"
#include "Egg.h"
Define_Module(Chicken);
void Chicken::initialize(void) {
EV << "Hi, I am a chicken, I am " << egg->eggAge*100 << " days old \n";
}
Egg.ned
package chickenegg;
simple Egg extends Chicken {
@class(Egg);
}
Egg.h
#ifndef EGG_H_
#define EGG_H_
#include <omnetpp.h>
#include "Chicken.h"
class Egg : public Chicken {
private:
void initialize(void);
public:
int eggAge = 2;
};
#endif /* EGG_H_ */
Egg.cc
#include "Egg.h"
Define_Module(Egg);
void Egg::initialize(void) {
EV << "Hi, I am an egg, I am " << eggAge << " days old \n";
}
Where am I making a mistake?
CodePudding user response:
As Lala5th and PaulMcKenize in the comments suggested, adding egg = new Egg();
in void Chicken::initialize(void)
method in Chicken.cc solved the issue.
CodePudding user response:
One mustn't create an instance of a class of simple module. According OMNeT Simulation Manual:
Simple modules are never instantiated by the user directly, but rather by the simulation kernel.
If you want to obtain an access to module egg
from chicken
, in the code of Chicken
use the following piece of code:
// in Chicken.cc
cModule *mod = getModuleByPath("^.egg"); // ^ means the parent module
if (mod) {
egg = dynamic_cast<Egg*> (mod);
if (egg) {
EV << "Hi, I am a chicken, I am " << egg->eggAge * 100 << " days old \n";
}
}
Reference: Finding Modules by Path