PDA

View Full Version : Object Composition



Andre008
25th February 2016, 21:33
Hello,

i have the following code, which has an object composition relationship between the class Group and Person:


dialog.cpp



#include "dialog.h"
#include "ui_dialog.h"

#include "group.h"

Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);


Group g1;
g1.setGroupId(1);

// this function should print the groupID
g1.p1.printGroupId();

}

Dialog::~Dialog()
{
delete ui;
}



group.h


#include "person.h"

class Group
{
public:
Group();

int getGroupId() const;
void setGroupId(int value);

Person p1;
private:
int groupId;

};


group.cpp


#include "group.h"

Group::Group()
{
}
int Group::getGroupId() const
{
return groupId;
}

void Group::setGroupId(int value)
{
groupId = value;
}


person.h


#include "group.h"


class Person
{
public:
Person();
void printGroupId();


};


person.cpp



#include "person.h"

Person::Person()
{
}

void Person::printGroupId()
{
//How it is possible to access the member variable groupID of the Group object to which this Person objects belongs ?
qDebug()<<"The GroupID is:";
}



Thx

anda_skoa
25th February 2016, 22:14
The group either needs to tell the Person about the group id, or let it access the group id.

Cheers,
_

Andre008
25th February 2016, 22:18
But how the group tell the person this, or how to give this access ?

anda_skoa
26th February 2016, 08:46
But how the group tell the person this, or how to give this access ?
Group has access to the person instance, it can call methods on it.

E.g. Group::setGroupId() can call Person::setGroupId()

Cheers,
_