is this possible - pointer to a classtype, that differs?

M

mandatory

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, 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 ?
 
P

Phil Staite

mandatory said:
How can i make different AClass:Hello() functions - without creating a new
classtype ?

Have the AClass::Hello() type function "call back" to the original
callers. These objects "know" what they are and can do the right thing
if you need unique behavior for each.
 
D

Donovan Rebbechi

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top