### Composition and cardinality in the code

Hello everyone,

I've got a doubt with cardinality. I can write code watching UML but I don't know how to respect cardinality.
How can I write properly a code respecting proposed cardinality?
In this case I have to write a code, using composition and cardinality 0,1 like in the picture:
http://imagizer.imageshack.us/v2/800x600q90/809/5pm6.jpg

I write down my code, do you think it's right? Please, let me know how can I get better with cardinality in the code for exemple 0 or * or 1,1 or 0,* . Thank you everybody!

 ``1234567891011121314151617181920`` ``````#include #include using namespace std; class G{}; class H { void association(G g){gp=&g;} private: G* gp; }; int main(int argc, char *argv[]) { return 0; }``````

> `void association(G g){gp=&g;}`
dangling pointer
hmm
Last edited on
maybe, should it be void association(G g){gp=g;} ?
then the cardinality would be 1,1
protest00 wrote:
maybe, should it be void association(G g){gp=g;} ?

It would still be a dangling pointer. When you pass a value into this function, it will copy it. You then set the pointer to the address of this copied value. This value is then destroyed after the function call is finished, and the pointer becomes a dangling pointer.

Pass a reference to a G type in order to solve that problem.

While it may not be directly related to your problem, it's still important to code it correctly.
Last edited on
For `void association(G g){gp=g;}` to be valid, `gp' should not be a pointer
The filled diamond in http://imagizer.imageshack.us/v2/800x600q90/809/5pm6.jpg
indicates a UML "Composition association relationship"
 A composition association relationship specifies that the lifetime of the part classifier is dependent on the lifetime of the whole classifier. http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/com.ibm.xtools.modeler.doc/topics/ccompasn.html

 ``123456789101112131415161718192021222324252627282930`` ``````struct G { /* ... */ }; struct H01 // cardinality 0 or 1 { H01() = default ; H01( const G& gg ) : g(gg) {} void associate( const G& gg ) { g.reset(gg) ; } private: boost::optional g ; // #include }; struct H0m // cardinality 0 to many { H0m() = default ; H0m( const G& gg ) : gs( 1, gg ) {} void associate( const G& gg ) { gs.push_back(gg) ; } private: std::vector gs ; }; struct H1m // cardinality 1 to many { H1m() = delete ; H1m( const G& gg ) : gs( 1, gg ) {} void associate( const G& gg ) { gs.push_back(gg) ; } private: std::vector gs ; };``````

(If you want to use pointers instead, `std::unique_ptr<G>` enforces sole ownership semantics.)
Topic archived. No new replies allowed.