using references and pointers and best practices

Hi Experts,

In the following code, is there any issues. Does it conform to C++ best practices.
should I be using a reference as the member variable?

Thank you.
class MyClass
{
   void setSomeObj(SomeObj& so);
   void getSomeObj(SOmeObj& so) const;

   private:
       SomeObj *_obj;

};

void MyClass::setSomeObj(SomeObj& so)
{
   // get the address of so
   _someObj = &so;
}

void MyClass::getSomeObj(SomeObj& so) const
{
   // get contents of pointer
   so = *_someObj;
}

Open in new window

ambuliAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

evilrixSenior Software Engineer (Avast)Commented:
I'd change it to...
class MyClass
{
   void setSomeObj(SomeObj& so);
   SomeObj const & getSomeObj(SOmeObj& so) const;
   SomeObj & getSomeObj(SOmeObj& so);

   private:
       SomeObj *obj_; // avoid leading underscores, without getting into detail the C++ standard reserves them for its own use

};

void MyClass::setSomeObj(SomeObj& so)
{
   obj_= &so;
}

SomeObj const & MyClass::getSomeObj() const
{
   return *obj_; // return a const reference
}

SomeObj & MyClass::getSomeObj()
{
   return *obj_; // return non-const reference (not a great idea, but better than returning a pointer)
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Infinity08Commented:
Who owns the SomeObj object ? What's its lifetime ? What's the MyClass object's lifetime ? Are there any other pointers/references to the SomeObj object ?
0
historychefCommented:
So the pointer you're storing as a private instance variable contains (when it is valid) the address of an object declared and defined outside of this class. Why? Without knowing, it's difficult to say whether this style is "best practice," but it seems to violate the first principle of OOP: encapsulate the data within the class definition, so you can control access to it with appropriate accessor methods. The code you have only allows you to control access to a pointer to the object, not to the object itself. To see why this isn't best practice, consider the following code:

Object newObj = new Object();
MyClass myObj = new MyClass();
myObj.setSomeObj( newObj );        // sets myObj._ptr = &newObj;
delete newObj;                                 // now myObj._ptr points to a non-existent object
// The next call to getSomeObj() will return garbage

The only way I would consider this to be even moderately acceptable (let alone "best") practice is if the class of newObj were a "friend" class of MyClass (as, for example, Container and Iterator classes are). Otherwise, this is a bug waiting to happen.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

ambuliAuthor Commented:
sorry for the late response. The MyClass represents a cache.  It stores object created by MySetter. getSomeObj is used by user.  as below.
class MyClass
{
   void setSomeObj(SomeObj& so);
   void getSomeObj(SOmeObj& so) const;

   private:
       SomeObj *_obj;

};

void MyClass::setSomeObj(SomeObj& so)
{
   // get the address of so
   if(_someObj != NULL )
   {
      delete _someObj;
   }
   _someObj = &so;
}

void MyClass::getSomeObj(SomeObj& so) const
{
   // get contents of pointer
   so = *_someObj;
}

class MySetter
{

}
MySetter::someFn()
{
   SomeObj *obj = new SomeObj();
   myClass->setSomeObj(obj);
   ...
}

class User
{
}

void User::someFn()
{
   SomeObj obj;
   myclass->getSomeObj(obj);

}

Open in new window

0
Infinity08Commented:
So are you saying that MyClass owns the SomeObj object ? If so, does it also free the memory once it's no longer needed ?

Btw, if that is all that MyClass does, I don't really see the point. Maybe what you really need, is a smart pointer ?
0
historychefCommented:
ambuli,

I'm confused. In the following code (taken from your sample above), where is _someObj declared? Or did you mean _obj? Perhaps you could help by using more meaningful variable names -- I'm getting lost in a forest of various flavors of "obj".

void MyClass::setSomeObj(SomeObj& so)
{
   // get the address of so
   if(_someObj != NULL )
   {
      delete _someObj;
   }
   _someObj = &so;
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.