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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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> g ; // #include <boost/optional.hpp>
};

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<G> 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<G> gs ;
};


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