Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ > Re: private mem...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 6 Topic 45825 of 47032
Post > Topic >>

Re: private member variables

by "3DCoderGuy" <nobody@[EMAIL PROTECTED] > May 9, 2008 at 03:35 PM

"wiskey5alpha" <wiskey5Alpha@[EMAIL PROTECTED]
> wrote in message 
news:d65408bd-b1da-4971-95d5-f8c72fd5d18d@[EMAIL PROTECTED]
> 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

{

   .

}



In Foo.h

class bar;          //A change to Bar doesn't cause everything that
includes 
Foo.h to recompile



class Foo

{

   Bar *m_bar;

public:

   Foo();

   ~Foo();

}



In Foo.cpp

#include "Bar.h"  // a change to Bar.h only causes Foo to recompile not 
everthing that includes Foo.



Foo::Foo() :

   m_bar = 0;

{

   m_bar = new Bar;

}



Foo::~Foo()

{

   if (m_bar)

   {

      delete m_bar;

      m_bar = 0;

   }

}



I hope this helps.

Mark
 




 6 Posts in Topic:
private member variables
wiskey5alpha <wiskey5A  2008-05-09 07:50:48 
Re: private member variables
James Kanze <james.kan  2008-05-09 08:07:07 
Re: private member variables
"3DCoderGuy" &l  2008-05-09 15:35:24 
Re: private member variables
"Jim Langston"   2008-05-09 09:00:57 
Re: private member variables
wiskey5alpha <wiskey5A  2008-05-09 10:15:03 
Re: private member variables
mlimber <mlimber@[EMAI  2008-05-09 10:35:38 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Jul 25 15:51:59 CDT 2008.