class, self reference problem

#include <iostream>
#include <string>
#include <list>

using namespace std;

class node
{
float ang, dist;
node* parent;
list <node*> kids; // an n-way tree structure

node() {}// constructor , empty function atm
void sprout_node();
void extend_dist();
};

void node::sprout_node()
{
node n;
n.parent->this;
// p.kids.emplace_back(n);
}

void node::extend_dist(){dist += 0.1;}


So my sprout_node method is wrong.
I want to
a.) create a new (child) instance of a node
b.) have the current instance be its parent
c.) put the new child in the kids list
Really don't know how to do it in c++
Anyone have any ideas? thanks
One naive solution:

1
2
3
4
5
6
7
8
9
10
# include <memory>
# include <vector>

struct node { 
  node(node* parent = nullptr): parent{parent} {}  
  void sprout_node() { children.push_back(std::make_unique(this)); }
private:
  node* parent;
  std::vector <std::unique_ptr <node>> children; 
};


There are two significant problems with this structure:
1. it cannot be copied; and
2. destruction of a large graph is prone to stack-overflow.
Last edited on
1
2
3
4
5
6
//a.) create a new (child) instance of a node
node *n = new node;
//b.) have the current instance be its parent
n->parent = this;
//c.) put the new child in the kids list
this->kids.emplace_back(n);


note that I'm using dynamic allocation, that's because you've defined list<node *> kids;
┬┐do you have a good reason for that instead of list<node> kids;?
do you have a good reason for that instead of list<node> kids;
Containers of incomplete type invoke undefined behavior unless the standard specifies otherwise. (Until C++17, which defines the usual behavior for list, forward_list and vector of incomplete type.)
See http://en.cppreference.com/w/cpp/container/list#Template_parameters
Last edited on
damn.
thank you.
1
2
3
4
5
6
void node::sprout_node()
	{
		node n;
		n.parent=this;
		kids.emplace_back(n);
	}


hi ne555,
is there a reason why your 6th line has 'this' pointing at the list?
in my latest attempt I just stuck n in the kids list like it was a normal list ( not a list of pointers ). Will this work?
Last edited on
Will this work?

Assuming that node::kids has type cv- std::list<node>, this is correct since C++17 (See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4510.html ), but before that, the program exhibits undefined behavior.

In real life, I would tend towards Boost.Container:
http://www.boost.org/doc/libs/1_65_1/doc/html/container/main_features.html#container.main_features.containers_of_incomplete_types
Last edited on
Registered users can post here. Sign in or register to post.