473,770 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Objects as private members...

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

Jul 23 '05 #1
5 2185
"pmatos" <po**@sat.ine sc-id.pt> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
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;
}; NB: style-wise, you'd actually use a reference rather than a pointer:
class B {
public:
A const& geta() const { return a; }
private:
A a;
};
or
class B {
public:
A * geta() const { return a; }
private:
A * a;
};


The (corrected) first option has several advantages:
- the lifetime of the data member a is clearly defined
(you know it will be constructed at the same time as B, etc)
- the const-semantics are also explicit (b.a is const if b is const)
- you'll avoid allocating a separate memory block for
the A object (possibly a performance issue).

The second approach, however, has the advantage that the definition
of A does not have to be seen to use class B. It is related to
the "pimpl" idiom, which is relatively common in C++.
See http://search.yahoo.com/search?p=pimpl+idiom
Hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 23 '05 #2

"pmatos" <po**@sat.ine sc-id.pt> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.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

Jul 23 '05 #3

Ivan Vecerina wrote:
NB: style-wise, you'd actually use a reference rather than a pointer:
class B {
public:
A const& geta() const { return a; }
private:
A a;
};

Still strange to me the diff between A * geta(...) and A & geta(...)...
I think I'll have to check that out. In both cases won't geta just
return a pointer to A, i.e., a block of memory containing the address
of the object itself?
or
class B {
public:
A * geta() const { return a; }
private:
A * a;
};


The (corrected) first option has several advantages:
- the lifetime of the data member a is clearly defined
(you know it will be constructed at the same time as B, etc)
- the const-semantics are also explicit (b.a is const if b is const)
- you'll avoid allocating a separate memory block for
the A object (possibly a performance issue).

The second approach, however, has the advantage that the definition
of A does not have to be seen to use class B. It is related to
the "pimpl" idiom, which is relatively common in C++.
See http://search.yahoo.com/search?p=pimpl+idiom


Just read about the idiom. Never heard about it before. Interesting but
not why I'm used to return the pointer.
Hope this helps,
Well, helped a lot. Thanks... At least just made think! :)
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form Brainbench MVP for C++ <> http://www.brainbench.com


Jul 23 '05 #4
pmatos wrote:
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.


I don't like either of those. Returning a non-const pointer to member
data opens up the possibility that someone will change it. Also, I
would avoid dynamically allocating the A object unless you absolutely
need to. It'll make things easier on yourself. So, use the first
example, but have geta return a const A *, or even better, a const A &.

This begs the question of why you need to return a handle to the A
object in the first place. In the true spirit of encapsulation, it
shouldn't matter to your users that a B object uses an A object for
internal data. Instead of providing a geta function, write member
functions that perform the desired operations on the B object. Let
them (instead of the user) modify the A object as needed. That way, if
you ever decide to change that A object to a Foo object, your public
interface doesn't have to change. Ideally, your users should be able
to stop reading your class header when they see "private:" (or
protected:) and they will have learned everything they need to know to
use the class.

Kristo

Jul 23 '05 #5
Hi Paulo,

This is a design choise for you. Both apporaches as advantages and
disadvantages. Hence the choise should be made according to your
design, future needs and most likely application of the class in a
context.

-vs_p...

Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
3937
by: Matteo Settenvini | last post by:
Ok, I'm quite a newbie, so this question may appear silly. I'm using g++ 3.3.x. I had been taught that an array isn't a lot different from a pointer (in fact you can use the pointer arithmetics to "browse" it). So I expected that when I run this program, I get both c1.A and c2.A pointing to the same address, and changing c1.A means that also c2.A changes too. ----- BEGIN example CODE -----------
12
2679
by: Manolis | last post by:
Hi, I was wondering if there is any way to make two objects of the same class to be able to access each other's private data, like this: class A { public: void access( const A& a ) {cout<<"a.value="<<a.value<<endl; } private: int value;
6
1473
by: Vic Sowers | last post by:
If I do this: function MyObject() { this.MyFunc = function () {alert("MyFunc called");} } obj1 = new MyObject(); obj2 = new MyObject(); do I get two copies of the code inside MyFunc?
5
1782
by: zqhpnp | last post by:
class String { public: String& operator=(const String& str); private: char* pdata; } String& String::operator=(const String& str) { if(this==&str)
0
17815
by: Nashat Wanly | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui06032003.asp Don't Lock Type Objects! Why Lock(typeof(ClassName)) or SyncLock GetType(ClassName) Is Bad Rico Mariani, performance architect for the Microsoft® .NET runtime and longtime Microsoft developer, mentioned to Dr. GUI in an e-mail conversation recently that a fairly common practice (and one that's, unfortunately, described in some of our...
24
3635
by: rdc02271 | last post by:
Hello! Is this too crazy or not? Copy constructor: why can't I copy objects as if they were structs? I have a set of simple objects (no string properties, just integers, doubles) and I have to copy the same object millions of times. So instead of writing in the copy constructor property1=SourceObject.property1 can't I use memory copy functions to do this faster? Is this too stupid? By the way, I'm a C++ newbie! But don't go easy on me...
3
3573
by: Sam Kong | last post by:
Hi group, I want to have some advice about immutable objects. I made a constructor. function Point(x, y) { this.x = x; this.y = y; }
31
1762
by: attique63 | last post by:
how could I write a program that will declare a class point. The class point has two private data members x and y of type float. The class point has a parameterized constructor to initialize both the data members i.e. x and y. The class point has a member function display() that display the value of x and y. Create two objects p1 and p2 with your desired data and display the values of x and y of p1 and p2. Now create a third object p3 by...
4
7142
by: =?Utf-8?B?Qnlyb24=?= | last post by:
When I try to serialize an instance of the LocationCell below (note Building field) I get an error in the reflection attempt. If I remove the _Building field it serializes fine. I tried renaming Building._Name to Building._BName in case the duplicate name was the issue, but that didn't help. Is there a native way to serialize nested objects, or will I have to write my own? public class LocationCell
0
9619
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.