philologon
philologon

Reputation: 2105

Aliasing property names in derived class?

I am writing my own Vector class by inheriting from my own Point class. The fields which I call x, y, and z in the Point class I would like to call i, j, and k in the Vector class. The same private double variables back the properties.

The approach I am using is to declare x, y, and z as private in the Vector class and set up i, j, and k as public, but with the same get/setters, like so:

Will this work okay, or am I setting myself up for heartache?

public class ptsVector : ptsPoint
{
   private double x { get { return x_; } set { x_ = value; } }
   private double y { get { return y_; } set { y_ = value; } }
   private double z { get { return z_; } set { z_ = value; } }

   public double i { get { return x_; } set { x_ = value; } }
   public double j { get { return y_; } set { y_ = value; } }
   public double k { get { return z_; } set { z_ = value; } }
   // methods elided for clarity
}

Note that the Point class has x_, y_, and z_ as protected doubles.

Upvotes: 4

Views: 1319

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

I think we need more info on how you are going to use these. If you don't need to refer to a ptsVector as a ptsPoint, then I would ditch the inheritance. Can you say a vector is a point? If not, then polymorphism is not appropriate here.

This particular example aside, I think aliasing a property is a Bad Idea, no matter what. It adds lots of complexity for no real benefit.

Upvotes: 3

McGarnagle
McGarnagle

Reputation: 102753

I would avoid doing this: just from a semantic standpoint, they are two different concepts and one doesn't really "inherit" the other. If anything, I would say a vector contains two points, as it is defined as the path from point A to point B.

As you say, you're setting yourself up for heartache when you start to add functionality to the classes. Any benefit you think you're deriving from this inheritance would best be pursued in a semantically correct way.

Upvotes: 2

Related Questions