By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,897 Members | 1,955 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,897 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Bora wrote:

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.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.