Reputation: 3
I have a Node.h file which introduces Node class and I have implemented methods and member variables of it in Node.cpp file. Now I need to use this class in the definition of another class but also I need some additional variables for implementation. I can't change the header files. So how can I do it?
Upvotes: 0
Views: 2418
Reputation: 57046
There's two ways to do it: inheritance and composition. If your new class is a Node with some additional features, then you should use inheritance as other people have suggested. If your new class needs to do things with a Node, but really isn't a Node, give the new class a data member of class Node.
By using composition, the new class doesn't get the Node interface, meaning that Node member functions don't automatically work. It doesn't get any protected
functionality (which the Node class probably shouldn't have anyway). It gets some insulation from possible future changes to Node, which could happen (adding new Node functions would add them to the new class if it used inheritance). It reduces coupling between the new class and Node, which is generally good.
Use composition when you can, and inheritance only when it makes things significantly easier.
To use composition, your new .h file would have:
#include "Node.h"
Node m_node;
or
class Node;
std::unique_ptr<Node> m_node; // or other desired pointer type
which requires explicit allocation (the std::unique_ptr
is there to delete m_node when the class member is deleted) and an extra layer of indirection (m_node->Foo()
rather than m_node.Foo()
). Using forward declarations rather than including .h files in .h files is good for large projects, as it tends to speed up compiles.
Then just call the Node public
functions in the workings of youre new class.
Upvotes: 0
Reputation: 968
That is what inheritance is for, just create a new class that inherits after Node, like so:
#include "Node.h"
class NewNode: public Node {
// New stuff goes here
}
//Edit
As mentioned in a comment, make sure the destructor is virtual.
Upvotes: 2