Hi everyone,
I'm trying to accomplish some node-based stuff and i'm trying to set some nodes to allow only some kind of nodes for connection. Now i might have somewhat of a design problem as it seems i can only achieve this behavior by using dynamic_cast<> which i have always heard to be a sign of poor coding design. Here's a small test i've made:The output i got from running this small test was:Code:#include <iostream> #include <stdexcept> class nodeA { protected: nodeA *m_node; public: virtual void connect(nodeA *node) { if (!node) { throw std::runtime_error("nodeA: Null pointer was passed"); } if (node==this) { throw std::runtime_error("nodeA: Can't connect to itself"); } m_node = node; std::cout << "nodeA: Connection to " << node << " performed \n"; } }; class nodeB : public nodeA { float somevar; // to make classes different double var1; public: virtual void connect(nodeA *node) { if (!node) { throw std::runtime_error("nodeB: Null pointer was passed"); } if (node==this) { throw std::runtime_error("nodeB: Can't connect to itself"); } if (!dynamic_cast<nodeB*>(node)) { throw std::runtime_error("nodeB: Wrong nodetype"); } m_node = node; std::cout << "nodeB: Connection to " << node << " performed \n"; } }; int main() { nodeA mNodeA; nodeA otherA; nodeB mNodeB; nodeB otherB; nodeA *nodePtr = &otherA; // start with an A node type std::cout << "\n"; std::cout << "mNodeA at " << &mNodeA << "\n"; std::cout << "otherA at " << &otherA << "\n"; std::cout << "mNodeB at " << &mNodeB << "\n"; std::cout << "otherB at " << &otherB << "\n\n"; try { mNodeA.connect(nodePtr); std::cout << "A----->A OK!" << "\n"; nodePtr = &otherB; mNodeA.connect(nodePtr); std::cout << "B----->A OK!" << "\n"; mNodeB.connect(nodePtr); std::cout << "B----->B OK!" << "\n"; nodePtr = &mNodeA; mNodeB.connect(nodePtr); std::cout << "A----->B OK!" << "\n"; std::cout << "If we got here no node exceptions were thrown so i'll leave while i'm winning..."; std::cout << "\n\n"; exit(0); } catch (const std::runtime_error& e) { std::cout << "Runtime error: " << e.what() << "\n\n"; } return 0; }Which looks exactly like i expected it to and it seems the way i want things to work out. My only doubt here is if using the dynamic_cast<> for this is a poor design and if there's a better way of implementing this behavior of A accepts A, B derives from A but only Accepts A and possibly other nodes derived from A.Code:mNodeA at 0xbfb92c64 otherA at 0xbfb92c5c mNodeB at 0xbfb92c48 otherB at 0xbfb92c34 nodeA: Connection to 0xbfb92c5c performed A----->A OK! nodeA: Connection to 0xbfb92c34 performed B----->A OK! nodeB: Connection to 0xbfb92c34 performed B----->B OK! Runtime error: nodeB: Wrong nodetype
Sorry for the long post and thanks in advance for any help.
Cheers



LinkBack URL
About LinkBacks



