On 2005-03-20, mandatory <ok*****@nptklooohs.ru> wrote:
Hi,
I have a class:
class Aclass
{
void Hello();
}
AClass::Hello()
{
printf ("Hello\r\n");
}
How can i make different AClass:Hello() functions - without creating a new
classtype ?
The reason i ask, is i have a list of classes,
C++ doesn't support "lists of classes", though there are many idioms that do
this. If you're using such an idiom, you should say which. If you mean "list
of objects", it's important to use the correct terminology ("list of classes"
means something completely different)
which all should contain a
pointer to the same classtype - but even though the functions are the same,
the code needs to be different.
I were wondering about something like "Friend" or similar ?
Assuming you mean list of objects:
one way is to use polymorphism:
class AClass {
public:
virtual void hello() const = 0;
};
class AClass1 : public AClass {
public:
void hello() const { printf("hello\n"); }
};
class AClass2 : public AClass {
public:
void hello() const { printf("HELLO\n"); }
};
list<smart_pointer<AClass> > x;
x.push_back(new AClass1);
x.push_back(new AClass2);
for (list<smart_pointer<AClass> >::iterator i =
x.begin(); i!=x.end(); ++i)
(*i)->hello();
Approach 2: callbacks
typedef void (*hello_function_t) ();
class AClass {
private:
hello_function_t f;
public:
AClass (hello_function_t f) : f(f) {}
};
Approach 3: callbacks via function objects:
class HelloFunction {
public:
virtual operator() const = 0;
};
class AClass {
private:
HelloFunction* f;
public:
...
then get different behaviour by deriving from HelloFunction
Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/