0

With the two classes below, I want to set b.i in the constructor of A. How do I do this?

I can't pass the value to the constructor of B, because I only get the value somewhere inside the constructor of A. I tried making A::A() a friend function of B, but that requires me to include a.hpp, which leads to circular inclusion. The only solution I can come up with is changing the type of b to B*. Are there better ways?

A.hpp:

#include "B.hpp"
class A {
private:
    B b;
public:
    A();
}

B.hpp:

class B {
private:
    int i;
public:
    B()
}

A solution I found

A logical solution is to make A a friend of B, so it can access i.

I had tried this before, but then it didn't work. Apparently that was due to an other problem, or I did it incorrectly, because now it does work.

Oebele
  • 581
  • 1
  • 4
  • 17
  • Regarding the marked as duplicate, I understand all that's in that link, have even used it before, but I don't see how that helps me with this issue. – Oebele Jun 07 '15 at 13:05
  • It's all about forward declaration of `class A;` that is needed to make it a `friend` in `B`. – πάντα ῥεῖ Jun 07 '15 at 13:22
  • I tried forward declaring `A` in `B`, but when I then added the line friend `A::A()` to `B`, the compiler still gave an error. Which makes sense to me, because the compiler needs to know that `A::A()` exists, so forward declaring is not enough. – Oebele Jun 07 '15 at 17:28
  • You can only make the whole class a friend, if it was forward declared. – πάντα ῥεῖ Jun 07 '15 at 17:29

1 Answers1

0

You could use the constructor initialization list for this purpose.

class B {
private:
    int i;
public:
    B(int i){this->i  = i;}
};

class A {
private:
    B b;
public:
    A(int i):b(i){}
};
Nivetha
  • 698
  • 5
  • 17
  • The value of i becomes available only in the constructor of A, due to an API call, so I cannot pass it from the outside. – Oebele Jun 07 '15 at 13:06