1

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;
};
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
CoderNoob
  • 11
  • 1
  • As a note, you should never write class, variable, function, ... names in UPPERCASE. UPPERCASE should only be used for macros. – t.niese Sep 21 '19 at 15:59
  • 4
    Possible duplicate of [Is std::vector copying the objects with a push\_back?](https://stackoverflow.com/questions/2275076/is-stdvector-copying-the-objects-with-a-push-back) – JaMiT Sep 21 '19 at 16:25
  • Also see [information about dangling references](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). – JaMiT Sep 21 '19 at 16:29
  • Yes you are right, the reference is lost when copying. For future reference, the problem is solved by assigning a pointer to the owner object AFTER all push_backs have been performed. I.e one needs to loop through the vector and assign pointers afterwards – CoderNoob Sep 21 '19 at 19:17

0 Answers0