0

I came across some code I don't understand. In a class B there is a pointer to a method of a different class A but the pointer has no variable. How can I call this method in class B? This is part of a larger project of someone else, i would like to preserve the existing code.

class A {
public:
  A *root() { return this; }
};

class B {
public:
  A *root();
};

I expected something like this

A *myA = root();

inside class B to work but i get linker error "undefined reference to ...". The question is more how this construction is called, what is it useful for and how to use it.

nopech
  • 19
  • 4
  • 1
    Would you be surprised if it was an `int`? Pointers are not special in that sense. Concerning the error you get, a little research should tell you what it means and how to fix it. That said, there is no "pointer to method" anywhere in the code you show. There is a method (or memberfunction) returning a pointer. – Ulrich Eckhardt Sep 22 '19 at 08:28
  • The method root() has no implementation. That's why you get a linker error. – jignatius Sep 22 '19 at 08:30
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Alan Birtles Sep 22 '19 at 08:37
  • `A*` ist just the return type of `B::root` if that’s what you are confused by. – Darklighter Sep 22 '19 at 08:49

1 Answers1

2

As in the comments standing, there is no implementation of B::root(). Maybe the code you have has beside the .h file a .cpp or .hpp file, where the implementation of B::root() stands - or there exists a library with it.

A valid implementation could be A* B::root() { return new A(); }. You can just grep for B::root.

To call B::root(), a simple B b; A* as = b.root(); is enough. Same as with A::root(), where a simple call could be A a; A* as = a.root();

class A {
public:
  A *root() { return this; }
};

class B {
public:
  A *root();
};

A* B::root() { return new A(); }

int main() {
  A a;
  B b;
  A* asa = a.root();
  A* asb = b.root();
  return 0;
}
codewerfer
  • 320
  • 2
  • 6
  • By the way, it makes no difference if you write `A* a` or `A *a`, both are a pointer to A, at compile time the whitespace between is ignored/removed. Stroustrup uses `A* a` in his books. – codewerfer Sep 22 '19 at 08:58
  • Thank you for your time and effort. In hindsight it is obvious... The problem was there was just a declaration, the implementation was never done. I added that and it worked just as expected. – nopech Sep 22 '19 at 09:08