473,396 Members | 1,775 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

private member variables

Hello all.

I have a design question.

assuming we have
class Bar {...} // body omitted for clarity

class Foo
{
// should Bar be implemented as a pointer or not here ?
Bar *m_bar; // OPTION 1
// or
Bar m_bar; // OPTION 2

.... // body omitted for clarity

Foo::Foo()
// OPTION 1
m_bar = new Bar;
m_bar.setID(1);
// or
m_bar.setID(1);

I have seen both of these methods used, so I am wondering if there
is any memory or speed differences between the two ?
Jun 27 '08 #1
5 1639
On May 9, 4:50 pm, wiskey5alpha <wiskey5Al...@gmail.comwrote:
I have a design question.
assuming we have
class Bar {...} // body omitted for clarity
class Foo
{
// should Bar be implemented as a pointer or not here ?
Bar *m_bar; // OPTION 1
// or
Bar m_bar; // OPTION 2
It depends somewhat on Bar, and what you're doing with it. In
general, use a value if you can, a pointer if you have to.
... // body omitted for clarity
Foo::Foo()
// OPTION 1
m_bar = new Bar;
m_bar.setID(1);
That would be m_bar->setID( 1 ) ;
// or
m_bar.setID(1);
I have seen both of these methods used, so I am wondering if
there is any memory or speed differences between the two ?
Probably not enough to worry about. On the other hand, using a
member object is a lot surer and more reliable.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 27 '08 #2
"wiskey5alpha" <wi**********@gmail.comwrote in message
news:d6**********************************@j22g2000 hsf.googlegroups.com...
Hello all.

I have a design question.

assuming we have
class Bar {...} // body omitted for clarity

class Foo
{
// should Bar be implemented as a pointer or not here ?
Bar *m_bar; // OPTION 1
// or
Bar m_bar; // OPTION 2

... // body omitted for clarity

Foo::Foo()
// OPTION 1
m_bar = new Bar;
m_bar.setID(1);
// or
m_bar.setID(1);

I have seen both of these methods used, so I am wondering if there
is any memory or speed differences between the two ?
I don't think you will see any significant change in memory or speed.

But the reasons why you use an instance of the object or a pointer to the
object would be many.

When you use an instance, the object is instantiated when the class Foo is
instantiated and destroyed when Foo is. But you have to declare the class
Bar for class Foo to us it. On a small class design that might not be a
problem. On large projects the dependency between headers could be
overwhelming.

When you us a pointer to the object you need to instantiate and destroy the
object yourself. But you don't have to declare the full class. E.g.

In Bar.h

class bar

{

Jun 27 '08 #3
wiskey5alpha wrote:
Hello all.

I have a design question.

assuming we have
class Bar {...} // body omitted for clarity

class Foo
{
// should Bar be implemented as a pointer or not here ?
Bar *m_bar; // OPTION 1
// or
Bar m_bar; // OPTION 2

... // body omitted for clarity

Foo::Foo()
// OPTION 1
m_bar = new Bar;
m_bar.setID(1);
// or
m_bar.setID(1);

I have seen both of these methods used, so I am wondering if there
is any memory or speed differences between the two ?
As others are stating,
Bar m_bar;
is preferred. When you can't, for whatever reason, then you would use a
pointer
Bar* m_bar;
or wrap Bar in a class hiding the pointer. Using pointers when you don't
have to brings up maintance issues that you have to remember to deal with,
new if you need to, if you do new make sure you delete, point it to the
correct place if you're not newing it, etc... Pointers are a level of
indirection and you should only add a layer of indirection when you have to,
or there is a good sound design issue it resolves.

--
Jim Langston
ta*******@rocketmail.com
Jun 27 '08 #4
On May 9, 10:50*am, wiskey5alpha <wiskey5Al...@gmail.comwrote:
Hello all.

[..]
Thank you all. I really appreciate the help !
Jun 27 '08 #5
On May 9, 10:50 am, wiskey5alpha <wiskey5Al...@gmail.comwrote:
Hello all.

I have a design question.

assuming we have
class Bar {...} // body omitted for clarity

class Foo
{
// should Bar be implemented as a pointer or not here ?
Bar *m_bar; // OPTION 1
// or
Bar m_bar; // OPTION 2

... // body omitted for clarity

Foo::Foo()
// OPTION 1
m_bar = new Bar;
m_bar.setID(1);
// or
m_bar.setID(1);

I have seen both of these methods used, so I am wondering if there
is any memory or speed differences between the two ?
To add to the other comments, you should use initializer lists rather
than the constructor body (http://www.parashift.com/c++-faq-lite/
ctors.html#faq-10.6), and prefer to use the constructor parameters to
initialize member variables and set class invariants rather than
manual setting things up as you do with Bar::setID(), which could
allow internally invalid objects to hang around and cause trouble.
(Consider also the named parameter idiom,
http://www.parashift.com/c++-faq-lit...tml#faq-10.18).

Also, to prevent memory leaks, you should generally use smart pointers
(cf. http://www.parashift.com/c++-faq-lit...html#faq-16.22
and the following FAQs) and RAII containers like std::vector (http://
http://www.parashift.com/c++-faq-lit....html#faq-34.1) rather than
raw pointers. In the first place, with smart pointers you needn't
destroy the created objects explicitly in your destructor, and in the
second place, you gain exception safety in your constructors (cf.
http://www.parashift.com/c++-faq-lit....html#faq-17.2) and
elsewhere. Consider:

class Foo
{
Bar *m_bar1;
Bar *m_bar2;
public:
Foo()
: m_bar1( new Bar( 1 ) )
, m_bar2( new Bar( 2 ) )
{}

~Foo()
{
delete m_bar2;
delete m_bar1;
}
// ...
};

If the construction of Foo::m_bar2 throws an exception (out of memory,
invalid parameter, whatever), then the memory from m_bar1 is leaked
since the destructor is not called unless the constructor completed
successfully. Probably better is to change the member variable types
from Bar* to std::tr1::shared_ptr<Bar(aka, boost::shared_ptr<Barif
your standard C++ library doesn't have TR1 yet) or similar. Then you
can drop the destructor altogether and you have exception safety in
your constructor (cf. the Law of the Big Two, http://www.artima.com/cppsource/bigtwoP.html),
but the rest of your code remains unchanged and happily oblivious that
it is now smarter.

One of your goals should be to write code that is easy to use
correctly and hard to use incorrectly, and another should be to let
the compiler do the work of releasing resources like memory, files,
and locks for you rather than doing it explicitly (Sutter and
Alexandrescu, _C++ Coding Standards_, Item 13 and
http://www.research.att.com/~bs/bs_faq2.html#finally).

Cheers! --M
Jun 27 '08 #6

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

Similar topics

3
by: IHateSuperman | last post by:
public class StaticField2{ public static void main(String args){ private int x, y; // <<== error 1 for ( y = 0 ; y < 100 ; y++){ x = StaticMethod(); System.out.println(" x = "+x); } } public...
10
by: Scott Brady Drummonds | last post by:
Hi, everyone, I'm still learning Python as I develop a medium-sized project. From my previous experience with C++, I've burnt into my mind the notion of information hiding. I'm having trouble...
3
by: Rajesh Garg | last post by:
Can we have private constructors and destructors? IF yes what is the use of such constructors or destructors.....in the sense where can these be implemented in a system................. I have...
19
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
2
by: Christoph Boget | last post by:
Let's take the following class: class MyClass { private int privateVar; public int PublicVar { get { return privateVar; } } public MyClass() {}
6
by: David Whitchurch-Bennett | last post by:
Hi There, I have created a very simple web user control, containing only a combo box. I have created a class which contains some private object variables, for example... Private _anObject as...
23
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624....
6
by: zfareed | last post by:
Is it possible to print an array that is declared from a class type that also contains private data members? I have declared an array in the main function and then set the values for the array...
8
by: David Veeneman | last post by:
Should a member variable be passed to a private method in the same class as a method argument, or should the method simply call the member variable? For years, I have passed member variables to...
5
by: fourpastmidnight | last post by:
Ok, before anyone gets on me ( ;) ), I'm developing on Windows 2000 with IE6sp1 (that's what my company uses). So no, I can't use Firefox, though I wish I could. Ok, with that out of the way, here's...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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,...

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.