0

Here is what UML looks like CLASS UML

ClassA has an pointer to ClassB, and ClassB has a pointer to ClassC. I was wondering if I can access functions of ClassA in ClassC without inheriting ClassA.

  • 1
    class C would need a pointer to class A – drescherjm Jul 06 '21 at 19:59
  • 1
    `C` would need a object of class `A`, (or pointer to one) to call the functions on. – NathanOliver Jul 06 '21 at 20:00
  • @drescherjm can we have some kind of API that does it, so C does not have entire knowledge of A.. – Yash Mehta Jul 06 '21 at 20:25
  • @NathanOliver can we have some kind of API that does it, so C does not have entire knowledge of A. – Yash Mehta Jul 06 '21 at 20:26
  • 1
    Sure, there is all sorts of things you can do. It can be as simple as giving `A` static functions that can be used by anyone. Without knowing what you want to do though, I can't really give you any concrete suggestions. – NathanOliver Jul 06 '21 at 20:29
  • Maybe you could try to use Callback functions. For more details I suggest you could refer to the link: https://stackoverflow.com/a/28689902/11872808 – Jeaninez - MSFT Jul 07 '21 at 05:46

1 Answers1

0

Q: I was wondering if I can access functions of ClassA in ClassC without inheriting ClassA.

A: Yes, it is possible to access functions of ClassA in ClassC. Either by calling static member functions of classA or by providing specific instance of classA to ClassC. It may look like that classA can be accesed by following the pointers in reverse direction (ClassC to ClassB to ClassA) but that is not possible. Pointers point to values only in one direction.

This is interesting question about differences between a class and instances of class (objects). The following example shows why there is no classA::callAnyMethod():

#include <iostream>

class B;
class C;

class A
{
    public:
        A(B *next, int value) : next_(next), value_(value) { }
        void af1() const { std::cout << value_ << "\n"; }
        static void af2() { std::cout << staticValue << "\n"; }

    protected:
        B *next_;
        int value_;
        static int staticValue;
};

int A::staticValue = 3;

class B
{
    public:
        B(C *next) : next_(next) { }

    protected:
        C *next_;
};

class C
{
    public:
        void cf1(const A &a) { a.af1(); }
        void cf2() { A::af2(); }
};

int main()
{
    C c;

    B b(&c);

    A a1(&b, 1);
    A a2(&b, 2);

    // a1 is first instance of class A.
    // One 'A::value_' is defined in a1 and is equal to 1.
    c.cf1(a1);

    // a2 is second instance of class A.
    // Second 'A::value_' is defined in a2 and is equal to 2.
    c.cf1(a2);

    // Without specific instance of class A, we can use only static member
    // 'A::staticValue' which is defined at file scope and is equal to 3.
    // 'A::staticValue' is not part of objects (instances) of class A.
    c.cf2();

    return 0;
}