user3191398
user3191398

Reputation:

Returning pointer to class member - should I avoid it?

I dont have experience in programming so I want to ask about your opinion. For example I have 3 classes:

class A
{
public:
   A(int size);
   int getSize();
private:
   int size_;
};

class B
{
public:
   A* getChild(int childNumber);
   int getNChildren()
   {
      return children.size();
   }
private:
   std::vector<A> children;
};

class C
{
public:
   void sumSize()
   {
       int sum = 0;
       for(int i = 0; i < member.getNChildren(); i++)
       {
            sum += member.getChild(i)->getSize(); // here I wonder if this is good style
       }
   }

private:
  B member;
};

Is this a bad practice? I know I can have method sumSize() in class B and return this sum, but can I do it in this way or in bigger program there will be a complication? So here is my main questions:

  1. Should I avoid returning pointer to member: A* getChild(int childNumber);
  2. Everything which refer to children, should be compute in class B?

Upvotes: 0

Views: 56

Answers (1)

Chip Grandits
Chip Grandits

Reputation: 357

I believe you are describing a container design pattern, which is well respected and useful. As the designer if you decide that member functions are public then you intend to let the "outside world" access them, and that decision depends upon what you are trying to accomplish.

Perhaps you don't want the outside world to modify this member, and so perhaps const A* getChild(int childNumber) might be what you want.

It is a good habit to think about "const-ness" as you design, all three of you public member functions in your example could be const (e.g int getSize() const) without affecting the functionality you have demonstrated.

One mistake here is the use of operator as a name of a private data member. operator is a reserved keyword in C++.

Upvotes: 1

Related Questions