haxpiotr haxpiotr - 25 days ago 6
C++ Question

Returning shared pointer, binary tree C++11,

I've got to create small binary tree for class using smart pointers. Everything is okay when ChildL and ChildR are public members and I use them directly, but I am supposed to create tree with private members and access via functions.
The result in console is just: root
Can you help me ? I am using visual studio 2015.

#include <iostream>
#include <memory>
#include <string>
using namespace std;

class Node
{
public:
Node(string n) : name(n) {}
shared_ptr<Node> getChildL()
{
return ChildL;
}
shared_ptr<Node> getChildR()
{
return ChildR;
}
shared_ptr<Node> createChildL(string n)
{
return shared_ptr<Node>(new Node(n));
}
shared_ptr<Node> createChildR(string n)
{
return make_shared<Node>(n);
}
string getName()
{
return name;
}
private:
string name;
shared_ptr<Node> ChildL, ChildR;
};

void PrintTree(shared_ptr<Node> tree)
{
if (tree)
{
cout << tree->getName() << endl;
PrintTree(tree->getChildL());
PrintTree(tree->getChildR());
}
}

int main()
{
shared_ptr<Node> root = make_shared<Node>("root");
root->getChildL() = root->createChildL("leaf");
PrintTree(root);
cin.get();
}

Answer

This member:

shared_ptr<Node> createChildL(string n) {
    return shared_ptr<Node>(new Node(n));
}

Doesn't assign to ChildL. It just creates a new node embeds it in a shared pointer and then returns it.

You might (I suppose) implement:

std::shared_ptr<Node> createChildL(string n) {
    ChildL=std::make_shared<Node>(n);
    return ChildL;
}

However that's not the best way. If all you're trying to do is encapsulation consider implementing get/set pairs:

void setChildL(const std::shared_ptr<Node>& left) {
    ChildL=left;
}

You presumably want to build a BinaryTree class to handle the insertion / removal of nodes in a manner obeying the tree invariant (e.g. ChildL->n <= n and ChildR->n >n for every node.).