I want to create a variable of type Foo. The class Foo consists of a variable called Bar bar_ which is filled directly in the constructor initialization. The thing is, class Bar has a reference to the interface IFoo& foo_. Foo2 is an object which derive from IFoo. But I do not want to create an variable of type Foo2, because I do not need it again. Only for the interface. (the class Bar is given code, I can not change). So I come with this solution:
Foo(int x, int y) : bar_(Foo2(x, y))
I do not get any error, but I ask myself, where the object Foo2 is now stored? Isn't it directly destroyed after the construction? This is why I added some more code, just creating another random object and checking if the values of foo changes. My supposition seems correct. The values of foo does have changed.
Questions:
- Is there any way, this code could work?
- Or do I have to add a variable of type Foo2 in the class Foo (or somewhere else)?
Code: https://onlinegdb.com/3sQ4X03ji
#include <stdio.h>
class IFoo
{
public:
virtual int GetSum() = 0;
};
class Foo2 : public IFoo
{
public:
Foo2(int x, int y) : x_(x), y_(y)
{
printf("Creating Foo2 with: x=%u, y=%u\n", x, y);
}
int GetSum() override
{
return x_ + y_;
}
int x_;
int y_;
};
class Bar
{
public:
Bar(Foo2 foo) : foo_(foo)
{
}
IFoo& foo_;
};
class Foo
{
public:
Foo(int x, int y) : bar_(Foo2(x, y))
{
}
Bar bar_;
};
int main()
{
Foo foo(1, 2);
Bar bar(Foo2(2, 3));
printf("The sum of foo is: %u (expected 3)\n", foo.bar_.foo_.GetSum());
printf("The sum of bar is: %u (expected 5)\n", bar.foo_.GetSum());
return 0;
}
Output:
Creating Foo2 with: x=1, y=2
Creating Foo2 with: x=2, y=3
The sum of foo is: 275680318 (expected 3)
The sum of bar is: 5 (expected 5)
Bar(Foo2 foo)beBar(Foo2& foo)? If not then refuse to complete the assignment as it contains undefined behaviourFoo2, why are you storing a reference to one (even if via reference to base i.e.Foo &) inBar? By doing so, you have introduced a requirement that theFoo2exist for the lifetime of the containingBar(otherwise any usage of the reference withinBars member functions will give undefined behaviour). If there is no usage of the reference byBars member functions, what is the purpose ofBarhaving the reference member at all?