PHcoDer
PHcoDer

Reputation: 1236

Passing pointer of an object to another class in its constructor

This question is somewhat related but still doesn't solves my problem. Consider two classes A and B:

class A{
public:
    A(int id, B* coordinator);
    virtual ~A();
    B *coordinator;
}
class B{
public:
    B(int id, int param2);
    virtual ~B();
    run();
}

void b::run(){
    while(true){
      A(1, this);
      A(2, this);
      //something else create which may create more A
    }
}

int main(int argc, char* argv[]) {
    B bObj(atoi(argv[1]), atoi(argv[2]));
}

In main function I create an object of class B type called as bObj. Constructor of B calls run() and B.run() goes in an infinite loop. Where it creates multiple objects of A. Now I want to pass a pointer of bObj to newly created objects of class A, so that they can access other public variables and functions of bObj. So I am passing this pointer while creating objects of A from B. And I have declared a class variable coordinator of B* type in class A. But I am getting this: Compiler error -> ISO C++ forbids declaration of ‘B’ with no type.

Please help me with this. I am fairly new to C++.

Upvotes: 2

Views: 4412

Answers (2)

Chor Sipahi
Chor Sipahi

Reputation: 546

Did you try forward declaration of class B? That should atleast partially solve your problem.

Upvotes: 1

WhiZTiM
WhiZTiM

Reputation: 21576

In your current code, the compiler sees the entity B in your constructor, but doesn't know it as a type since it is yet to encounter such type declaration.

To solve your problem, You should simply forward declare B. And remember the ; semi-colon at the end of each class definition

class B;                        //forward declaration

class A{
public:
    A(int id, B* coordinator);
    virtual ~A();
    B *coordinator;
};                              //remember the semi-colon!

Upvotes: 1

Related Questions