meysamimani
meysamimani

Reputation: 335

Class with a std::vector of another class objects

I have two classes ( A and B)

I need to do something that when I make an object of class A (i.e. A obj()) a vector of class B that points to the objects of class A be constructed.

i.e. if I make an object of class A named obj(), then I want the first element of vector in class B (i.e. vector<'A*'> objects ) to be declare by obj().

 objects[0] = obj()

The code:

class B;
class A
{
public:
    A(int _location)
    {
        location = _location;
        pointer_B->redefine(this); // here in this line(14) I get two errors
    }

private:
    int location;
    B* pointer_B;
};

class B
{
public:
    void redefine(A* cur_obj)
    {
        objects.push_back(cur_obj);
    }

private:
    vector<A*> objects;
};

the errors are:

use of undefined type B   (line 14)    
left of '->redefine' must point to class/struct/union/generic type (line 14)

Upvotes: 2

Views: 1520

Answers (2)

JeJo
JeJo

Reputation: 33092

As @IgorTandetnik pointed out in the comments you have circular dependency between the class A and B. The solution is to separate the declarations and definitions either to header-source files and include the headers accordingly or put the definition of functions after the declaration of classes in the same translation unit.

class B;
class A
{
public:
    A(int _location);
    // .... other declarations  
};

class B
{
public:
    void redefine(A* cur_obj);
    // ...
};
// definitions 
A::A(int _location) {
    location = _location;
    pointer_B->redefine(this);
}

void B::redefine(A* cur_obj) {
    objects.push_back(cur_obj);
}

Other remarks:

That means, change to:

class A
{
public:
    explicit A(int _location, B *obj);
   //^^^^^^^                 ^^^^^^^^^
    ....
}

A::A(int _location, B *obj)
    : location{ _location }
    , pointer_B{ obj }
{
    pointer_B->redefine(this);
}

Upvotes: 1

liweiliv
liweiliv

Reputation: 41

```
class B;
class A
{
public:
    A(int _location);
private:
    int location;
    B* pointer_B;
};

class B
{
public:
    void redefine(A* cur_obj)
    {
        objects.push_back(cur_obj);
    }
private:
    vector<A*> objects;
};
A::A(int _location)
{
        location = _location;
        pointer_B->redefine(this);
}

Upvotes: 0

Related Questions