I'm relatively new to c++. I have a binaryTree class, that contains Nodes. Inside binaryTree, I want the "addleft" method to take in a node (and the potential subtree attached below it) and just "point" the root.left pointer to the "inputnode", without deep copying the node and its entire subtree that could come with it during the process.
struct Node {
int val;
Node* left;
Node* right;
Node(int val) : val(val), lc(nullptr), rc(nullptr) {}
Node() : val(0),lc(nullptr), rc(nullptr) {}
};
class binaryTree {
public:
Node root;
int size;
binaryTree(const Node& node) : root(node), size(1) {}
addleft(const Node& inputnode) {root.left=&inputnode;} //the problem is here
};
I'm under the impression that its common for functions to use take in parameters using "const type& variable" (Correct me if I'm wrong), so I use it here in "addleft" method. But now its bad because I can't assign "inputnode" to "root.left" since constant node object/reference can't be assigned to nonconstant pointer of root.
One option is to deep copy the "inputnode" and assign its address to root.left, but I'm trying to avoid that.
Is there any way for me to implement what I want the "addleft" method to do without changing the "const Node& input", or should I just not use "const Node& input" here? If I choose to abandon the "const Node& input" parameter, is it good conventions for me to write two "addleft" methods, one taking in "Node& input", the other "Node&& input", so I can deal with both temporary variables and nontemporary variables?
Edit: I'm told that using "Node& input" and "Node&& input" like below would lead to dangling pointers.
void addleft(Node& node) {
root.lc=&node;
}
void addleft(Node&& node) {
root.lc=&node;
}
However when I tested it, it still seems to run normally, with root.lc still pointing towards a Node of value 12 after the program ends. What am I missing?
int main () {
binaryTree a(Node(15));
a.addleft(Node(12));
cout<<a.root.lc->val<<endl;
cout<<"finished"<<endl;
}