Bartek Gąsior
Bartek Gąsior

Reputation: 21

vector of custom objects with pointer to another object

I'm working on student project and looks like I'm stuck. I've created a class named Bone where I have a pointer to another Bone object. In another class I have vector of Bone objects. I'm reading values to the vector from file and it is working fine. I'm also able to check if the child pointer is != NULL but I can't get values like name etc. What am i doing wrong?

Bone.h

class Bone {
public:
    Bone();
    char name[30];
    Bone *child = NULL;
    Bone *sibiling = NULL;
};

The other class

std::vector<Bone> skeletonBones; 

for (int i=0; i<skeletonBones.size(); i++){
        Bone *bone, **boneTmp;
        bone = &skeletonBones[i];
        if (&bone->child != NULL){
            boneTmp = &bone->child;
            cout << "child - " <<  << endl;  //here is the point where I have no idea how to print the child name
        }
        else
            cout << "no child" << endl;
    }

I appreciate any help.

Upvotes: 2

Views: 59

Answers (1)

I.S.M.
I.S.M.

Reputation: 131

#include <iostream>
#include <vector>

class Bone 
{
public:
    Bone();

    std::string name;

    Bone * child    { nullptr };
    Bone * sibiling { nullptr };
};

int main() 
{
    std::vector < Bone > skeleton_bones; 

    // add values to skeleton_bones

    for (std::size_t i = 0; i < skeleton_bones.size(); ++i)
    {
        Bone * bone = &skeleton_bones[i];
        if (bone->child)
        {
            Bone * child = bone->child;
            std::cout << "child is : " << child->name << std::endl;
        }
        else
            std::cout << "no child" << std::endl;
    }

    return 0;
}

Upvotes: 1

Related Questions