"pmatos" <po**@sat.inesc-id.pt> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
Hi all,
I have a style question. I've been for long programming in Lisp-like
languages and C when I need a low-level language. Now, I'm programming
for professional reasons in C++ (which I had programmed in before but
only in college) and I'm getting to like it, however I'm having some
issues with style.
For example,
If I have an object which I define as a private member of a class, for
example:
A and B are classes and class B has a private members which is an A.
Now, the question is, should this 'a' private members of B with type A
be a pointer or should it be an A object. In code (as near as real C++
code as possible):
class A {};
class B {
public:
A * geta() const { return &a; }
private;
A a;
};
or
class B {
public:
A * geta() const { return a; }
private:
A * a;
};
Apart from the fact that I need to initialize a in the second example,
are there are any efficiency, lack of style issues in any of these
approaches? Which one is used, or recommended. Oh, need to mention that
this question refers to the case when I don't need a to change at all.
I only use a by it's contents and along an object B live I don't want
to destroy a and create a new one.
Any comments?
Cheers,
Paulo Matos
Unless there's a specific reason to use a pointer, I always prefer to keep
the object itself. That frees you from having to manage the lifetime of the
object yourself, for one thing.
That said, I would hesitate to provide a function that returns a pointer to
a data member (especially a private one).
For one thing, you've said it's private, but if you return a pointer to it
then an external user can modify the contents of that private member
directly. Not always a bad thing, but I tend to avoid it unless I have a
good reason.
Privacy issues aside, it also makes it possible that someone who has
obtained that pointer might try to use it after the object which returned it
has been destroyed, resulting in undefined behavior.
My general preference would be to add methods to B for
setting/getting/modifying the members of that internal A object. This would
hide the fact that there's an A at all inside of B (from an outside user of
B), and prevent any problems with a B object being destroyed while someone's
got a handle to its internal A object.
Or, if A is some very simple structure and all I want is to get data from it
(and not modify it in the B object), then I might return a copy of the
object instead.
Finally, I might reconsider making it private at all, and simply allow
direct access to it. But that would depend on the situation, and my reason
for making it private in the first place.
-Howard