2

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)
JeJo
  • 30,635
  • 6
  • 49
  • 88
meysamimani
  • 315
  • 2
  • 12
  • 2
    Since you have a circular dependency between two classes, you need to declare their methods first, and define them separately, after the definition of both classes is complete. You cannot combine the declaration and definition the way you do currently. – Igor Tandetnik Jul 17 '19 at 03:35

2 Answers2

1

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);
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
0
```
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);
}
liweiliv
  • 31
  • 5