Kevin
Kevin

Reputation: 2730

calling method from parent class

First: I know my question is not about a parent class, but I don't know how this structure is called and I thought parent would be the easiest to describe it.

I have two classes defined like this:

class class_a {
    void foo() {
        //stuff
    }
};

class class_b {
    class_a A;
    void foo() {
        //more stuff
    }
};

I want class_b::foo(); called when certain requirements are met in class_a::foo(); It's possible to just set a variable in class_a and check for it in class_b::foo(); but I was wondering if there is a more elegant solution to this.

note: class_b is and can not be derived from class_a.

Upvotes: 0

Views: 154

Answers (3)

Péter Török
Péter Török

Reputation: 116266

For the terminology, class_b contains, or owns an instance of class_a.

For calling class_b::foo from class_a::foo, you need to make the instance of class_b available to class_a::foo. This can be achieved either by adding a member variable to class_a as you noted, or a parameter to class_a::foo (both of which creates a circular dependency between the two classes, which is better avoided - you should rather rethink your design). Or via a global variable (which is usually not recommended either, as it makes it hard to follow the flow of control, to unit test, etc.).

Upvotes: 0

Pete
Pete

Reputation: 4812

Not sure I completely understand what you are trying to do, a more concrete example would be helpful, but perhaps this does what you want:

class class_b;

class class_a {
    void foo(class_b* b);
};

class class_b {
    class_a A;
    void foo() {
        A.foo(this);
    }
    void foo_impl() {
        // stuff based on requirements in a::foo
    }
};

void class_a::foo(class_b* b) {
    //stuff
    if (conditionsMet()) {
        b->foo_impl();
    }
}

Upvotes: 1

Not_a_Golfer
Not_a_Golfer

Reputation: 49195

One thing you can do is create a third class that abstracts this behavior, whether it derives from both, or is just independent.

Upvotes: 0

Related Questions