Hello,
Is it impossible to instantiate an object of class A in a method of class B ?. In other words, Do we have to instantiate objects just in the main ?.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Experiment
{
public:
staticvoid Run (........);
.
.
.
};
class MyNode : Class Experiment
{...};
class SourceNode : class MyNode
{...};
class RelayNode : class MyNode
{...};
class DestinationNode : class MyNode
{...};
According to the above, I want to instantiate an object of class SourceNode in the "Run" body but I have got an error: ‘SourceNode’ was not declared in this scope
//Enumeration to decide on the type of object.
enum MyClassesEnum
{
MyNodeType,
SourceNodeType,
RelayNodeType,
DestinationNodeType
};
class Experiment
{
public:
//I am using an enumeration to determine the type to instantiate.
//I am also changing the return type. Otherwise, how were you going to return the new object?
static Expermient* Run(MyClassesEnum objectType);
};
class MyNode : public Experiment
{ };
class SourceNode : public MyNode
{ };
class RelayNode : public MyNode
{ };
class DestinationNode : public MyNode
{ };
Experiment* Expermient::Run(MyClassesEnum objectType)
{
Experiment *r = 0;
switch (objectType)
{
case MyNodeType:
r = new MyNode;
break;
//Etc. You get the idea. Add the rest here.
}
return r;
}
Please note that your compiler has no idea what a "SourceNode" is when it reads the Run() function for the first time. So you'd have to do something like class SourceNode; before the beginning. And then in your cpp file (which I'm assuming you have) just do what you'd normally do.
Just make sure that you don't use your "run" function in your constructor, because lol, since SourceNode is based off of Experiment the run function will be cyclical and you'll crash your compie =]