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)
1
  • 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. Commented Jul 17, 2019 at 3:35

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.