how to best instanciate a new class

Started by
12 comments, last by doynax 18 years, 5 months ago
You could pass a struct pointer or a reference.

struct POD{ par1 a; par2 b; par3 c;};class FOOBAR{    POD m_POD;public:    FOOBAR(POD* pPOD)     {       assert(pPOD);     // validate parameter       memcpy((void*)&m_POD,pPOD,sizeof(POD));  // Cast is evil!    };};


Yes, I know the C-style cast is evil.
This saves stack bashing, but costs you a level of indirection within your class.
Alternatively, you can unwrap the passed pointer in the constructor, and not have the indirection:

class FOOBAR{   par1 m_a;   par2 m_b;   par3 m_c;public:      FOOBAR(POD* pPOD)   {       assert(pPOD);       m_a = pPOD->a;       m_b = pPOD->b;       m_c = pPOD->c;   };};


This works well if you're creating a lot of instances with similar parameters, or parameters that don't change much - you simply tweak your single instance of the argument struct as you go along.
Winterdyne Solutions Ltd is recruiting - this thread for details!
Advertisement
Why not:

struct POD{ par1 a; par2 b; par3 c;};class FOOBAR{    POD m_POD;public:    FOOBAR(POD* pPOD)     {       assert(pPOD);     // validate parameter       m_POD = *pPOD;    };};
Functionally the same. And less evil. :-)


Winterdyne Solutions Ltd is recruiting - this thread for details!
How about using private inheritance instead of a local object to get rid of the extra level of indirection?

This topic is closed to new replies.

Advertisement