Re: Call order
sreeni wrote:
Can anyone suggest some mechanism where i can control the order of
function calls
Example
Base class has some methods(say 3 methods) used by
both derived class 1 , derived class 2
in derived class1 & 2 all these methods are invoked but the order is
different
Is there mechanism of making generic interface saying
from derived class 1 (inside a function) call base class methods (1 ,
2 ,3)
from derived class 2 (inside a function) call base class methods (3 ,
1 ,2)
If the order is set by the derived class and should be known by the base
class (and used by it), then an array of pointers to members (if all
those functions have the same type) would do. If the functions have
different types, then you're stuck with making two protected functions
which will call those three functions in those two patterns and letting
the derived classes either call them or provide the data (flag, pointer
to member) which will allow selecting one protected function or the
other. Example:
----------------------------- same type
#include <iostream>
#include <ostream>
class Base {
protected:
void (Base::*p[3])() const;
public:
void f1() const { std::cout << "Base::f1\n"; }
void f2() const { std::cout << "Base::f2\n"; }
void f3() const { std::cout << "Base::f3\n"; }
void doit() {
for (int i = 0; i < 3; ++i) {
(this->*(p[i]))();
}
}
};
class Derived1 : public Base {
public:
Derived1() {
p[0] = &Base::f1; p[1] = &Base::f2; p[2] = &Base::f3;
}
};
class Derived2 : public Base {
public:
Derived2() {
p[0] = &Base::f3; p[1] = &Base::f1; p[2] = &Base::f2;
}
};
int main() {
Derived1 d1;
std::cout << "Derived1:\n";
d1.doit();
Derived2 d2;
std::cout << "Derived2:\n";
d2.doit();
}
------------------------------------- different types
#include <iostream>
#include <ostream>
class Base {
protected:
int order[3];
public:
void f1() const { std::cout << "Base::f1\n"; }
void f2(int) { std::cout << "Base::f2\n"; }
void f3(char,char) { std::cout << "Base::f3\n"; }
void doit(int a, char c1, char c2) {
for (int i = 0; i < 3; ++i) {
switch (order[i]) {
case 1: f1(); break;
case 2: f2(a); break;
case 3: f3(c1, c2); break;
default: throw "Wrong order value";
}
}
}
};
class Derived1 : public Base {
public:
Derived1() {
order[0] = 1; order[1] = 2; order[2] = 3;
}
};
class Derived2 : public Base {
public:
Derived2() {
order[0] = 3; order[1] = 1; order[2] = 2;
}
};
int main() {
Derived1 d1;
std::cout << "Derived1:\n";
d1.doit(42, 'a', 'b');
Derived2 d2;
std::cout << "Derived2:\n";
d2.doit(42, 'a', 'b');
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask