I have a setup of a child, parent and grandparent classes. One grandparent have several parents,stored in a vector, and each parent have several children, also stored in a vector. Each object owns a reference to its owner.
In MAIN I set the ID-variable of the grandparent and parent to 1 respectively, but when i access the ID of the childs parent it is null. However when i access the childs parents grandparent is is 1 as expected.
Why is the child parents id not 1?
#ifndef HEADERH_H
#define HEADER_H
#include <vector>
class CHILD;
class PARENT;
class GRANDPARENT;
class CHILD{
public:
int id;
const PARENT &parent;
CHILD(PARENT &parent):parent(parent){};};
class PARENT{
public:
int id;
const GRANDPARENT &grandparent;
std::vector<CHILD> children;
PARENT(GRANDPARENT &grandparent):grandparent(grandparent){};};
class GRANDPARENT
{
public:
int id;
std::vector<PARENT> parents;
GRANDPARENT(){};
};
#endif
Source file
#include "Headerh.h"
#include <iostream>
int main(){
GRANDPARENT grandparent;
for(int i=0; i<=5; i++){
PARENT parent(grandparent);
for(int i=0; i<=5; i++){
CHILD child(parent);
parent.children.push_back(child);
}
grandparent.parents.push_back(parent);
}
grandparent.id = 1;
grandparent.parents[1].id = 1;
int test(grandparent.parents[1].children[1].parent.id);
int test0(grandparent.parents[1].children[1].parent.grandparent.id);
std::cout<<test<<" "<< test0<<std::endl;
return 0;
};