-adding a node of the correct type causes the derived class overloaded virtual function to correctly add the node.
-adding a node of the incorrect type defaults to the base class virtual function which reports a general invalid message.
so my goal is to have a Node* type return an identifying pointer of its Derived type so that the correct function is called from the Derived : Diagram type (using that derived pointer as the indentifier for the function signature).
currently the code always prints - "Error: wrong type of node for this type of diagram" - which indicates it is still being passed as a Node* type and not as a Derived : Node* type or atleast, the virtual function in the Base Diagram class is being called in preference to the Derived Diagram versions.
have i got the wrong idea? will this fail no matter how i attempt it?
Note: i understand i can change to Derived::addNode(Node*), to get something that will add the nodes, however i want to enforce restriction on the type of node added to the particular type of diagram
Expand|Select|Wrap|Line Numbers
- ERD* diagramERD = new ERD;
- DFD* diagramDFD = new DFD;
- vector<Diagram*> diagramList;
- diagramList.push_back(diagramERD);
- diagramList.push_back(diagramDFD);
- vector<Diagram*>::iterator activeDiagram = diagramList.begin();
- Datastore* myData = new Datastore;
- Entity* myEntity = new Entity;
- Node* myNodeData = new Datastore;
- Node* myNodeEntity = new Entity;
- (*activeDiagram)->addNode(myData->getMyType());
- (*activeDiagram)->addNode(myEntity->getMyType());
- (*activeDiagram)->addNode(myNodeData->getMyType());
- (*activeDiagram)->addNode(myNodeEntity->getMyType());
- (*activeDiagram)->addNode(dynamic_cast<Datastore*>(myData));
- (*activeDiagram)->addNode(dynamic_cast<Entity*>(myEntity));
- (*activeDiagram)->addNode(dynamic_cast<Entity*>(myData));
- (*activeDiagram)->addNode(dynamic_cast<Datastore*>(myEntity));
Expand|Select|Wrap|Line Numbers
- class Node {
- public:
- virtual void checkMyType() {
- cout << "I am a Node";
- }
- virtual Node* getMyType() {
- return this;
- }
- };
- class Datastore : public Node {
- public:
- virtual void checkMyType() {
- cout << "I am a Datastore";
- }
- virtual Datastore* getMyType() {
- return this;
- }
- };
- class Entity : public Node {
- public:
- virtual void checkMyType() {
- cout << "I am an Entity";
- }
- virtual Entity* getMyType() {
- return this;
- }
- };
- class Diagram {
- public:
- virtual void addNode(Node *newNode) {
- cout << "Error: wrong type of node for this type of diagram" << endl;
- }
- };
- class DFD : public Diagram {
- public:
- virtual void addNode(Datastore *newDatastore) {
- cout << "DFD::Adding ("; newDatastore->checkMyType(); cout << ") to nodeList" << endl;
- }
- };
- class ERD : public Diagram {
- public:
- virtual void addNode(Entity *newEntity) {
- cout << "ERD::Adding ("; newEntity->checkMyType(); cout << ") to nodeList" << endl;
- }
- };