Class methods operating on arrays of objects of the same type as itself.

B

Bora

Should a class be allowed to operate on an array of classes of the same type
as itself?

Say,

class X {
.....
void func( X* x);
}

void X::func(X* x) { ...}

....

X a = X();
X b[3] = { X(), X(), X() };

a.func(b);


Or is this a bad idea, and the function should better be moved to the class
that will need to call this method?

Thanks,
Bora
 
K

Karl Heinz Buchegger

Bora said:
Should a class be allowed to operate on an array of classes of the same type
as itself?

Say,

class X {
....
void func( X* x);
}

void X::func(X* x) { ...}

...

X a = X();
X b[3] = { X(), X(), X() };

a.func(b);

Or is this a bad idea,

That depends on the situation.

Eg.
X is a 'book'and func represents the operation search.

a.func(b)

would then be: search if book 'a' is rerpesented in the collection
of books b.

In this case I would opt for a seperate class 'library'. The library
manages all the books, thus the operation turns around:

library.search( a );

Here introducing a new class solved the problem nicely.

If on the other hand X eg. represents say a geometric line
and foo represents the operation 'intersect', the operation

a.func( b )

would read in plain english: dear line 'a', please intersect
yourself with all the lines I give to you and tell me if
there is an intersection.

IMHO nothing wrong with that.

In the first case I managed to come up with a meaningful
entitiy for the collection of X, the library. The library
has some functionality on its own, and can be viewed as
such a single entity on its own.
For the second example I can't come up with something like that.
Or, well I could come up with something equivalent: A line
usually is part of a drawing, thus a drawing consists of lines
So i could do:
line.intersect( drawing )
or
drawing.intersect( line )

on the other hand I just want to know the intersection of 2 lines
that may be overkill and the original would be better.

You see. It all depends on the current situation.
and the function should better be moved to the class
that will need to call this method?

That could also be a choice. As said it depends on the situation.
In programming there is seldom a 'one size fits all' situation.
 

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,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top