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