0

I have the error "invalid use of 'this' in non-member function"

What is the correct way to write the code to avoid this error.

tree.h:

#ifndef TREE_H
#define TREE_H

template <typename T>
class Node;

class Tree
{
public:
    Tree();

    template <typename TNodeType>
    Node<TNodeType> elaborate(Node<TNodeType> &node);

    Tree* self();

    void doSomething();
};

template <typename TNodeType>
Node<TNodeType> createNew() {
    Node<TNodeType> model(this); //<-- ERROR HERE
    return model;
}

#endif // TREE_H

node.h:

#ifndef NODE_H
#define NODE_H

#include <tree.h>

template <typename TNodeType>
class Node
{
public:
    Node(Tree *tree);

    TNodeType current();

private:
    Tree *_tree;
};

template <typename TNodeType>
Node<TNodeType>::Node(Tree *tree):
    _tree(tree)
{
    _tree->doSomething();
}

template <typename TNodeType>
TNodeType Node<TNodeType>::current()
{
    //some code here
}

#endif // NODE_H

Solved.

In tree.h I skipped the declaration of:

template <typename TNodeType>
Node<TNodeType> createNew();

And I had forgotten in the definition "Tree::" before "createNew()"

I agree that this question could have been avoided ;-). Sorry

Sebtm
  • 7,002
  • 8
  • 29
  • 32

2 Answers2

4

createNew() is a free function (i.e. not a member of a class), and therefore has no notion of this.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    Good answer, though I've never heard the term "free function" before. Is that a common term? I've only heard it called a "static member function" or "static method". – abelenky Jul 18 '13 at 12:26
  • 1
    Static member functions (or static methods, though the term "method" is unusual in the C++ community) are functions declared inside a class with the keyword static. Free functions are declared outside a class. And yes, that's the usual term for them. – Sebastian Redl Jul 18 '13 at 13:12
2
template <typename TNodeType>
Node<TNodeType> createNew() {
    Node<TNodeType> model(this); //<-- ERROR HERE
    return model;
}

It's really no member function. this is keyword of C++ language, that can be used only in member functions.

ForEveR
  • 55,233
  • 2
  • 119
  • 133