How do you reference class object inside said class constructor?

Hello!

Okay assume you have a class:
1
2
3
4
5
6
7
8
9
10
11
class Foo
{
    private:
        int a;
        int b;
    public:
        Foo(int argument);
        ~Foo();

        friend Class Bar;
};


and a second class:
1
2
3
4
5
6
class Bar
{
...
    public:
        static void change_a_b(int argument, Foo fooObject);
};


With the following function
1
2
3
4
5
void Bar::change_a_b(int argument, Foo fooObject)
{
    fooObject.a = ...;
    fooObject.b = ...;
};


So what I want to do is create a Foo object like so:
Foo fooObject(argument);
where argument is an int.

But Bar::change_a_b(int argument, Foo fooObject) function would be inside Foo::Foo(int) constructor.

Since the object would be in the process ob being created, how can you pass it to a function, inside the constructor?

EDIT: to make thinks clearer, that's what I mean:
1
2
3
4
5
6
Foo:Foo(int argument)
{
    Bar::change_a_b(argument,/*FOOOBJECT HERE*/)

    ...
}


Thank you in advance,

Regards,

Hoogo
Last edited on
Whenever the implementation looks complex, you have to ask yourself: Is this really the best possible design? Is there no simpler alternative?
Not really, I scratched my head for a while and I really have to do it that way. It's for a game I'm working on. Why are you asking? Is there no way to possibly do it that way?
There's probably a better way. But this may do what you're asking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

class Foo;  // forward reference

class Bar {
public:
    static void setFoo(int arg, Foo& foo);
};

class Foo {
    int a, b;
public:
    Foo(int arg) { Bar::setFoo(arg, *this); }
    void print() { std::cout<< a <<','<< b <<'\n'; }
    friend class Bar;
};

void Bar::setFoo(int arg, Foo& foo) {
    foo.a = arg / 2;
    foo.b = arg * 2;
}

int main() {
    Foo f(42);
    f.print();
}

Last edited on
@tbp

Thanks a lot, this is exactly the answer I was looking for!
EDIT: Well my complier is telling me that my function "does not take 2 arguments" even though I declared it and defined it correctly. The function call is correct too. I don't understand.
We can't see your code nor entire compiler messages, so how could we comment?
@keskiverto

My bad I was going to post the whole code but I had to go. I managed to sort it, turned out i had circular dependencies messing the whole thing up.

Thanks you a lot for your time though.

Regards,

Hoogo.
Topic archived. No new replies allowed.