1

I am unsure of the correct access specifier for the member var isMouseOverYard. In the snippet I don't have plans to inherit from House. Option 1 is more consistent with the base class (if I were to inherit from either class I can check whether the mouse is over the object/yard). However, option 2 is more accurate of my current intention, if I do not inherit from House. Is there a convention in regards to this usage?

class Object
{
protected:
    virtual bool isMouseOverObject() const;
};

Option 1

class House : public Object
{
protected:
   virtual bool isMouseOverObject() const override;
   bool isMouseOverYard() const;
};

Option 2

class House : public Object
{
protected:
   virtual bool isMouseOverObject() const override;

private:
   bool isMouseOverYard() const;
}
user870130
  • 565
  • 1
  • 8
  • 16

4 Answers4

2

My general rule of thumb is constraining the visibility to the biggest possible extent. I.e. I would make isMouseOverObject private in House class.

Michal Hosala
  • 5,570
  • 1
  • 22
  • 49
1

Both the options are just fine, option 2 is better, since the supporting methods could be private to your class, hidden from others, being privately confined and accessible to the class members

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
1

It doesn't really matter. I'd leave it protected because it's more flexible in the future, and it's a const method anyway so doesn't risk damaging anything too much if someone "misuses" it.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

The convention, at least by Bjarne Stroustroup if I remember correctly, is to never have protected data. This might seem tempting at times, but it's almost always better to only access data-members through get/set functions. These functions can then be made protected, making them available to derived classes but not to the outside world.

Therefore, in your case, I would go for Option 2, and consider to add some simple get/set functions in case you need them.

EDIT: I was misled to thinking this question was about a variable instead of a function due to a typo by the OP.

JorenHeit
  • 3,877
  • 2
  • 22
  • 28
  • @MichalHosala: the original code in the question missed out the `()` so it looked like a data member. – John Zwinck Oct 30 '14 at 08:33
  • Whoops... I glanced over this too damn quick. Thought the isMouseOverYard was a variable. I'll delete my answer. Edit: @JohnZwinck That explains it... – JorenHeit Oct 30 '14 at 08:33