-1

I want to push objects of class B type in vector<B> obj present in class A. However I'm getting some weird errors. I tried some examples but all of them were storing pointer objects, whereas I want to store a copy. Kindly suggest a fix.

class A{
    public:
    string name;
    vector<B> obj;
};

class B{
string characteristics;
A* pt_A;
};

int main(){
//Reading a xml file into vectors;
//Objects and their vector declaration
A e1;    
B e2;

vector<A> vec_A;  //Node lst
vector<B> vec_B;  //Edge lst

vector<A>::iterator ptr1, ptr2;

for(ptr1 = vec_A.begin(); ptr1 < vec_A.end(); ptr1++){
    for(ptr2 = vec_B.begin(); ptr2 < vec_B.end(); ptr2++){
        if(ptr1->name == "abc")
            ptr2_2->obj.push_back(&(*ptr1));
 }}

Even if all code is commented out in main, compiler reports:

Error: B was not declared in this scope vector<B> obj;

Error: Template argument 1 is invalid. vector<B**>** obj

Error: Template argument 2 is invalid

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    Can you show a real code example that you're working with, instead of this not-code. There can be many reasons for various compilation errors. Without a [mre] it is unlikely that anyone will be able to explain anything to you. – Sam Varshavchik Mar 02 '21 at 12:07
  • 1
    we cannot help you with code that you do not show us. Please include a [mcve] in the question. – 463035818_is_not_an_ai Mar 02 '21 at 12:07
  • quality of the question aside, it looks like the problem is just that you need to move definition of `A` before definition of `B`. You cannot create a vector of `B`s before the compiler knows what `B` is – 463035818_is_not_an_ai Mar 02 '21 at 12:09
  • Edited the code for perspective – user12061536 Mar 02 '21 at 12:20
  • @largest_prime_is_463035818 , I think you've correctly pointed out the mistake. However, if you look at the code now, Class B also has a Class A pointer member. If class B is shifted before A, compiler is indicating A* member as out of scope. Could you suggest a fix? – user12061536 Mar 02 '21 at 12:25

1 Answers1

0

A needs to know the definition of B when it has a std::vector<B> member (*). On the other hand, B only needs a declaration of A when it has a A* member:

class A;    // declare A

class B{
    string characteristics;
    A* pt_A;
};

class A{    
    public:
    string name;
    vector<B> obj;
};

(*) = Actually the details are a bit more involved, see here: How can an incomplete type be used as a template parameter to vector here?.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185