How do I reference another class into another class in C++? - c++

I've been trying to reference another class inside of a class in C++ and I have no idea how.
I have created a small program to demonstrate the issue
#include <iostream>
class foo{
public:
int variable1 = 012;
};
class bar{
public:
int getFooVariable(){
return variable1; // How would I get bar to refrence foo in foobar?
}
};
class foobar{
public:
bar p1;
foo p2;
};
int main(){
foobar fb;
std::cout << fb.p1.getFooVariable(); << std::endl;
return 0;
}
How would I solve this problem?

You're looking for dependency injection:
class foo
{
public:
int variable1 = 012;
};
class bar
{
foo _foo;
public:
bar(foo& fooInjected) :
_foo(fooInjected)
{}
int getFooVariable() { return _foo.variable1; }
};
There is an idea of inversion of control: bar has no control over the creation of foo instance, which is created outside. It's a common way to inject for instance a service. It's also a very important way to loosely couple classes working together and to mock and to test them. But here foo is a concrete class, instead and ideally you're refering only an interface (c#) or an abstract class (c++) in bar. Which concrete class is behind is out of control of bar. I recommend M. Seeman's book Dependency Injection in .NET to understand this completely.
or inheritance:
class foo
{
public:
int variable1 = 012;
};
class bar: public foo
{
public:
int getFooVariable() { return variable1; }
};
Here, bar builds up heavily on foo. bar is a "richer version" of foo if this makes sense. This is what to choose if there is a high cohesion inside bar.
Invoking a variable through another's instance function is a most horrid idea, that goes against class cohesion:
int getFooVariable(foo* foo) { return foo->variable1; }

Sorry to change the formatting, here's a solution:
#include iostream
class foo
{
public:
int variable1 = 012;
};
class bar
{
public:
int getFooVariable(foo* foo)
{
return foo->variable1; // How would I get bar to refrence foo in foobar?
}
};
class foobar
{
public:
bar p1;
foo p2;
};
int main()
{
foobar fb;
std::cout << fb.p1.getFooVariable(&(fb.p2));
<< std::endl;
return 0;
}
You can add a parameter to the getFooVariable() function to take a foo* reference. The reference can be found when you call the function.

Related

How to use MOCK_METHOD on a virtual function from a different class inside a Mock?

I am trying to use EXPECT_CALL to set the return value of the function that resides in a different class than what the mock class inherits from.
In the following snippet, I was wondering if there's a way to use EXPECT_CALL on someFunction() that's a public function of Bar inside a unit test through bar object of UnitTest class but it seems to error out.
One thing I know is I would need to use MOCK_METHOD for someFunction to override it to expect EXPECT_CALL but not sure how could I do inside the Mock class?
// Bar.hpp
class Bar
{
public:
virtual bool someFunction();
};
// Foo.hpp
namespace sw::foo_state
{
class Foo
{
Bar _bar;
public:
Foo(Bar&& bar) : _bar(std::move(bar)) {}
void TestFunction()
{
_bar.someFunction();
}
};
};
// MockClass.hpp
namespace sw
{
class Mock : public foo_state::Foo
{
Mock(Bar&& bar) : Foo(std::move(bar)) {}
};
};
// UnitTest.cpp
using namespace sw::foo_state;
class UnitTest
{
public:
Bar bar;
auto ptr = std::make_unique<Mock>(std::move(bar));
};
TEST_F(UnitTest, Test)
{
EXPECT_CALL(bar, someFunction()).WillOnce(Return(true)); // error: ‘class sw::foo_state::Bar’ has no member named ‘gmock_someFunction’; did you mean ‘someFunction’?
ptr->TestFunction();
}
EDIT:
You only need to change your class Foo constructor to accept a pointer or a reference to take advantage of class Bar polymorphism:
class Bar
{
public:
virtual bool someFunction()
{
return true;
}
};
class Foo
{
public:
Foo(Bar& bar): _bar{ bar} {}
void TestFunction()
{
std::cout << _bar.someFunction() << std::endl;
}
private:
Bar& _bar; // can also be std::unique_ptr<Bar> if you prefer to own the object
};
struct MockBar : public Bar
{
MOCK_METHOD0(someFunction, bool());
};
using testing::Return;
TEST(xxx, yyy)
{
MockBar mBar;
// ON_CALL(mBar, someFunction()).WillByDefault(Return(false)); // if you don't want to force expectation
EXPECT_CALL(mBar, someFunction()).WillOnce(Return(false));
Foo foo(mBar);
foo.TestFunction();
}

How to acess another member class object from within class

Im relatively new to cpp. Im currently trying to write new testcases for a class foo,
Class foo2 {
Public:
Getsomevariable();
// do something
}
Class foo {
Private:
Foo2 foo2_obj;
}
Class testfoo {
protected:
Foo foo_obj;
}
TEST_F(testfoo, getsomevariabletest)
{ // ? How to access getsomevariable method of foo2 from foo_obj
Temp = foo_obj?
ASSERT_EQ(100,Temp);
}
Now Im testing using object of foo, but how should I be able to access foo2.Getsomevariable() from foo object?
Please help
I created a main to demonstrate the purposes of this, but tweak it for your own intended purpose.
class foo2 {
public:
std::string Getsomevariable() {
return "Hey!";
}
};
class foo {
public:
foo2 foo2_obj;
};
int main() {
foo f;
std::cout << f.foo2_obj.Getsomevariable();
}

Pass function of an object to another object

I want to pass function of one object to another function as an argument. Below code is only for indication of the problem, (not realistic code). How can function IdNeeded can take function getNextId of class Bar?
class Foo
{
public:
void IdNeeded(getNextId);
}
class Bar
{
public:
int getNextId()
{
return ++id;
}
private:
int id = 0;
}
int main()
{
Bar bar;
Foo foo;
foo.IdNeeded(bar.getNextId); // foo will get id = 1
Foo anotherFoo;
anotherFoo.IdNeeded(bar.getNextId); // anotherFoo will get id = 2, because "id" is already incremented by one for foo object
}
I tried to use std::function, function pointer, std::bind, but unfortunately could not reach a final solution.
Provide a proper call back definition, and use a lambda to pack your object Foo:
#include <functional>
class Foo
{
public:
void IdNeeded(std::function<int()> f){ f();}
};
class Bar
{
public:
int getNextId()
{
return ++id;
}
private:
int id = 0;
};
int main()
{
Bar bar;
Foo foo;
foo.IdNeeded([&](){return bar.getNextId();}); // foo will get id = 1
}

Opposite of friend declaration

Say we have a class that has a private constructor, through friend we can allow some specific class(es) to still create objects of this class:
class Foo
{
friend class Bar;
private:
Foo();
};
class Bar
{
Bar()
{
//create a Foo object
}
};
Now what if I want the opposite of friend, where Foo looks like this:
class Foo
{
//enemy/foe??? class Bar; (if only)
public:
Foo();
};
And then no method of Bar can access the Foo constructor/ make an object of Foo but other classes can (because it's public).
class Bar
{
Bar()
{
Foo foo; //compiler error
}
};
Is such a construct possible or am I stuck with keeping Foo private and adding friends for all the classes?
Such a thing does not exist, and it would be extremely pointless. Imagine you have a situation like this:
class Foo
{
enemy class Bar;
public:
Foo() {}
};
class Bar
{
void evil() { Foo{}; }
};
Nothing prevents the implementor of Bar from doing this:
class Bar
{
void evil() { do_evil(*this); }
};
void do_evil(Bar &self)
{
Foo{};
}
do_evil is not a member of Bar (it's a global function), and so it's not an enemy. Such non-friendliness could therefore be trivially circumvented.
It cannot be done really, but maybe following is enough for you:
template <typename T> struct Tag {};
class Foo
{
public:
template <typename T>
Foo(Tag<T>) {}
Foo(Tag<Bar>) = delete;
// ...
};
And so asking "creator" to "identify" itself.
class Bar
{
Bar()
{
Foo foo{Tag<Bar>{}}; //compiler error
// Foo foo{Tag<void>{}}; // valid as we can cheat about identity.
}
};
There is no such concept in C++.
Public attributes will always be public, but you can limit the exposure of Foo by making the constructor protected, for instance, and only visible for selected classes (although limiting friend is advised). Perhaps also make Foo as a protected class of Bar2 because only Bar2 or its children will actually use it.
As it has already been sayed by others, your desire breaks the idea of encapsulation because you cannot always know who your enemies are.
But, still, there is a possibility to get (almost) what you want:
#include <type_traits>
struct enemy; // We need a forward declaration of your enemy
struct my_class {
// The access is done using a factory, where the caller has to tell
// us his own name
template <class T>
struct make{
static_assert(!std::is_same<T,enemy>::value,"you are my enemy.");
friend T;
private:
my_class operator() () { return my_class{}; }
};
private:
my_class(); // This is the constructor we care about
};
struct no_enemy {
void bar() {
my_class a = my_class::make<no_enemy>{}(); // works
}
};
struct enemy {
void bar() {
my_class b = my_class::make<enemy>{}(); // error: static_assert failed
my_class c = my_class::make<no_enemy>{}(); // error: foo is "private"
}
};

C++ Method chaining with classes

I'm attempting to do method chaining, however, instead of using the Methods in "Foo" I want to a constructor of a class (which is inherited from the base class):
class Bar {
public:
Bar() {
std::cout << "This is bar";
}
};
class Foo : public Bar {
public:
Foo() {
cout << "This is foo";
}
};
So my main would look like the following:
Foo f = Foo().Bar();
Why is this not possible in C++/C++11? Also, is there a way in which I can integrate this standard, or would I have to create an method in "Foo" which calls the constructor to "Bar"?
Edit:
class Bar {
public:
Bar() {
}
Bar& Options() {
cout << "sf";
return *this;
}
};
class Foo : public Bar {
public:
Foo() {
}
};
And then in main:
Foo F = Foo().Options();
Your updated question is illegal because Bar::Options() returns a reference to a Bar and you don't provide a way to convert a Bar to a Foo object.