-1

I have a class (C) with a member class (B) which tracks a third class (A). What's the proper syntax to call the public member functions of A via C and B? Or did I screw up my pointers?

#include <iostream>

class A
{
    public:
        void Hello() const {std::cout<<"World."<<std::endl;};
};

class B
{
    const A* aa;                    // Pointer can change, data cannot.

    public:
        const A* *const aaa;        // Pointer and pointed value are const.

        B() : aaa{&aa} {};
        void SetPointerToA(const A& aRef) {aa = &aRef;};
};

class C
{
    B b;

    public:
       B* bb;                       // Provide access to public members of B.

       C() : bb{&b} {};
};

int main()
{
    A aTop;
    C c;

    c.bb->SetPointerToA(aTop);      // Tell c.b to modify itself. No problems here.

    c.bb->aaa->Hello();             // <==== Does not compile.

    return 0;
}

gcc 5.2.0 complains about the call to Hello() :

error: request for member 'A:: Hello' in '*(const A**)c.C::bb->B::aaa',
which is of pointer type 'const A*' (maybe you meant to use '->' ?)
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Twiggy
  • 3
  • 1
  • @OlegBogdanov `aa` is private. And `aaa` is a double pointer. – Igor Tandetnik Jan 01 '17 at 03:17
  • `(*(c->bb->aaa))->Hello()`. You brought this upon yourself by your, shall we say, unconventional arrangement of having members that are pointers to other members. – Igor Tandetnik Jan 01 '17 at 03:18
  • 1
    Why are you making this so complicated. Remember [KISS](https://en.wikipedia.org/wiki/KISS_principle) – Ed Heal Jan 01 '17 at 03:19
  • `const A* *const aaa;` is just... no, don't do that. A simple accessor function would be much better and easier to work with. For example `const A* GetPointerToA() { return aa; }` – TheUndeadFish Jan 01 '17 at 05:29

1 Answers1

3

If you pay close attention, you would notice that aaa is a double pointer. Therefore, it should be:

(*c.bb->aaa)->Hello();

Having said that: these classes look very fragile. They don't comply with the Rule Of Three, and, thusly, things are going to break at every possible opportunity...

Community
  • 1
  • 1
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Thanks. I don't doubt that there's a better way to do it; this was more of an exercise in "can I?" rather than "should I?" – Twiggy Jan 03 '17 at 16:58