Link to home
Start Free TrialLog in
Avatar of VR_
VR_

asked on

What a way is more OOPer ?

I must to implement Quaternion and Complex numbers classes. I began so:

template <class T>
class Quaternion
{
 public:
  ...
  Quaternion(); // few kinds of Ctors
  ...
 private:
  T w,x,y,z; // w+xi+yj+zk;
};

I have 3 ways to continue:

1-st way:

template <class T>
class Complex1
{
  public:
   ...
   Complex1(); // few kinds of Ctors
   ...

  pirvate:
   Quarterion<T> q;  // I use the q as complex number
   // and its y,z fields initialized by zero;
};

2-nd way:
template <class T>
class Complex2:public Quarterion<T>
{
  public:
  ...
  Complex2(T a, T b):Quarterion(a,b,0,0){}
  // yet few needed Ctors
  ...
};

3-rd way:
template <class T>
class Complex3:private Quarterion<T>
{

//  Additional question (accordingly I add points):

  How can I to declare here function from Quarterion class so that they should public (I don't want that user of    Complex3 class should be able to use function from Quarterion beside of function I'll permit for using)?
};




What way from these is prefer ?



Thank you.
Avatar of yonat
yonat

This is known as the ellipse-circle dilemma (or the rectangle-square dilemma). The basic answer is that you should do what makes more sense in your context, and not necessarily reflect what mathematicians consider to be the true taxonomy.

For more info see http://ootips.org/ellipse-circle.html
ASKER CERTIFIED SOLUTION
Avatar of jasonclarke
jasonclarke

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of VR_

ASKER

I implement it through aggregation, although before it I tried private inheritance, where I meet with next problem:
I've adjusted access control to member function which I need in Complex for example:

template <class T>
class Quaternion{
...
public: Quaternion<T> operator+ (const Quaternion<T> q);
...
};

template <class T>
class Complex:private Quaternion<T>{
...
using Quaternion<T>::operator+;
...
};

and in user code:

...
Comlpex c1(1,2),c2(3,4),c3;
c3=c1+c2;
cout << (c1+c2);
...

// of course I have comp. error. So, although I have access to op+ in Quaternion I cannot use it with Complex parameters !
I tried partialy solution as definition
operator Quaternion<T>(), but anyway returned value is Quaternion<T>  :(
> So, although I have access to op+ in Quaternion I
> cannot use it with Complex parameters !
> I tried partialy solution as definition

it just won't work as you have it, this kind of exposure of Quaternions methods is a bad idea... how will you deal with:

Quaternion c1;
Complex    c2, c3;
....
c3 = c1 + c2;

this would be bad.  

This is exactly one of the cases I described above... substitutability fails here.  (and by making Quaternions methods public, you are in effect implementing a kind of selective public inheritance).