RandomUser42
RandomUser42

Reputation: 109

Passing instance of own class to another

Assuming I have these classes (question marks mark the question what I need to pass here):

class A
{
  ...
  public:
  void pass()
  {
     B ins;
     ins.doSth(?????);
  }
};

class B
{
  ...
  public:
  void doSth(const A &sth)
  {
    ...
  }
}

int main()
{
  A te;
  te.pass();
}

Can you pass an instance of your own class or is this just an example of a failed class structure on my side?

Upvotes: 4

Views: 1063

Answers (2)

Raindrop7
Raindrop7

Reputation: 3911

Your class "contains" an instance of each other so you'll face an error of undeclared types. To solve this issue you need to use forward declaration.

And you'll face another problem:

If your methods doSth() and pass() are defined inlinlely then you'll face a problem: "using incomplete types". The workaround this is to implement these methods outside the class so that each object has been fully constructed before used.

The program may look like:

class A;
class B;

class A{
  public:
    void pass();
};

class B{
  public:
      void doSth(const A &sth){
  }
};

void A::pass(){
    B ins;
    ins.doSth(*this);
}

int main(){
  A te;
  te.pass();

  return 0;
}

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92321

The current object in a member function is *this. You can pass that to another function.

You will have to consider how the classes depend on each other, and that one class cannot use the other class until the declaration is complete.

This would work though:

class A
{
  //...
  public:
  void pass();
};

class B
{
  //...
  public:
  void doSth(const A &sth)
  {
    //...
  }
};


// Here both classes are completely declared

void A::pass()
{
   B ins;
   ins.doSth(*this);
}


int main()
{
  A te;
  te.pass();
}

Upvotes: 3

Related Questions