Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In effective c++ Item 22, Scott Meyers say data member must be in private.

My question is, if there is class A, which is parent of class B and C, and A has data member "int id".

if A put "int id" in private, class B and C should use A's getter and setter, which cause reduction in performance.

example code in below.

C++
class A
{
public:
  int getId() { return id; }
  void setId(int id) { id_ = id; }
private:
  int id_;
};

class B : public A
{
public:
  int getId() { return A::getId(); }
  void setId(int id) { A::setId(id); }
}

class C : public A
{
public:
  int getId() { return A::getId(); }
  void setId(int id) { A::setId(id); }
};


I'm confused. Anybody help me what I should do?
Posted

First, see solution 1, it explains the issue pretty well.


In addition to that, the getId and setId functions (in your case) are implicitly inline, so you don't have to bother with reduction in performance in this case.

 
Share this answer
 
v2
1)First note, the classes B and C inherits getID() and setID() from class A (that is the parent for both) so you should delete them from class B and class C!

2)In generally the performance lost by using of get or set methods can be ignored, and it is recommended to use get() and set() in place of direct access.

3)If you want to access directly the id__ directly from class B or C you could change its access from private to protected.
 
Share this answer
 
Comments
Young Hyun Yoo 3-Feb-14 4:03am    
Thanks
Shmuel Zang 3-Feb-14 4:10am    
5'ed. See my addition.
Raul Iloc 3-Feb-14 9:14am    
Yes, your right, there are inline methods.
CPallini 3-Feb-14 4:26am    
5.
Raul Iloc 3-Feb-14 9:13am    
Thank you for your vote!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900