Nested class public method takes parent class as input - c++

I found this in a 3rd party codebase
class Foo {
public:
class Log {
public:
static Log method(Foo& foo);
};
};
I'm omitting many other methods from both classes for conciseness. It compiles, but it is giving me a hard time when trying to create python bindings around it via pybind11. Is this an acceptable practice or should I simply refactor the class to extract this Log class out of it?

This is a common practice if the Log class needs access to the data of Foo class. But it is also totally acceptable to write the Log class as other or friend class. In case of independent class you may need the appropriate getters for the Log class.

Related

Command design pattern with friend class in C++

The situation: I have to handle and take action on various commands, which can be encapsulated in the command design pattern. So right now I have
class Command {
virtual void applyCommand(IFoo& foo) = 0;
virtual ~Command() = default;
};
and of course I inherit this interface into my individual command classes.
However now, I realize that just passing IFoo isn't enough. I want to be able to access private data members in my ConcreteFoo class. I justify this break in encapsulation because when it comes down to it, all these objects are basically just helper functions for my ConcreteFoo class. I'm fine with them being strongly coupled because one way or the other, I have to write these methods, and doing the CDP makes it more readable.
So, I change my class to
class Command {
virtual void applyCommand(ConcreteFoo& foo) = 0;
virtual ~Command() = default;
};
and in my ConcreteFoo class I declare
friend class Command;
However, friendship apparently is not inherited into the subclasses of Command, the classes that actually do the work. So I can't actually get access to the data I need.
My current thoughts on solving this are:
1.) Take the L and just handle this without the CDP
possible, but I don't really want to take this route if I can avoid it
2.) Make data members in ConcreteFoo public
no
3.) Make data members in ConcreteFoo protected, and somehow make Command a subclass of ConcreteFoo
no
4.) Manually declare each Command subclass a friend, so like
friend class CommandA;
friend class CommandB;
friend class CommandC;
friend class CommandD;
...
decent, but might not scale well. on the plus side, if I forget to friend, it should fail at compile time
None of these options are particularly appealing to me. Is there something else I can do?
You’re basically working on visitor pattern (your Command class is a visitor to Foo classes).
One way to go around this, you might have a public interface of Command (applyCommand non-virtual) and virtual implementation(s) (applyCommandImpl virtual). You can make Command itself a friend and Command::applyCommand could extract the necessary data and pass it to the particular applyCommandImpl.
Normally, you’d simply extract the necessary parameters and pass those. However, if you really want to access all members, then you might do this: have the members of Foo in a struct (say, Foo1DO, as in data object) and inherit from it privately to have Foo1. Then you can have a simple getter to reach Foo1DO from Foo1 in applyCommand.

Is there a way for me to wildcard a friend class in C++?

I'm using gtest to unit test a cpp class. Consider a situation in which I'd like to make the test class a friend of the actual class, so it can unit test its private state. This works fine for me. The problem is that while using the very helpful TEST_P macro which allows you to parameterize test instantiation, the framework mangles the test name a bit.
So I have something like
class FooTester {
FooTester() {}
}
TEST_P(FooTester, TestCoolFeature) {
// test my cool feature that needs access to Foo's internal state
}
which is great but to allow this I must provide
class Foo {
friend class FooTester_TestCoolFeature;
}
we can see through macro magic gtest creates a new class I haven't explicitly declared which is a combination of the test class and the test method name.
This is ostensibly fine but a bit ugly. It would require me to add a new friend class for each new test method which requires this access. The only real, if unlikely, problem is that if gtest were to change its implementation and mangle the class names differently, it could break my tests.
Is there a way to use some #define magic or similar to declare all FooTester* classes as friends?
Do not use friend classes for that. If you would like to access Foo from FooTester, inherit it publicly:
class FooTester : public Foo
{
FooTester() {}
}

Mock Methods that are not virtual

I have a class say A like mentioned below :
class A
{
void show()
{}
int data(int x)
{}
.....
};
I need to mock the class - since the member functions are not virtual - can I design my mock class like mentioned below:
class MockA : public A
{
MOCK_METHIOD0(show, void ());
MOCK_METHIOD1(data, int (int));
}
Can I implement this way and is there a chance from MockA to miss out mocking of
any function of class A?
Objects created using MockA will ever anyway land up calling class A actual method implementation?
Generally for this case you do not have the mock inherit from A and instead use a compile time mechanism to select whether to use an implementation class or a mock class. E.g. templating everything that uses A and then instantiating the templates with either A or MockA, to replace the production class with the mock one in the testing setup. Any methods that are not implemented in the mock, but which are called, result in a compile time error. The use of the macros in the mock definition are pretty much the same even though the methods are non-virtual.
The hard part is replacing the class everywhere. Templates, referencing the class name via a macro, or using the same class name and making sure only one is linked are all possibilities.

how to add a function to a lib class without overriding it

I've a case in which I need to add some functions to a game engine class I'm using for a VR project without overriding the class it self:
The engine class name is AnnwaynPlayer that contains many useful methods to control the player, now I'm in the networking phase so I need to add 2 extra methods to this lib class which are setActive() and setConnected(), what is the best way to do this ?
If you can't touch the class itself then you probably want to use inheritance. This is one of the main goals of object-oriented programming -- to be able to add/change the behavior of an existing class without altering it. So you want something like:
class MyAnnwaynPlayer : public AnnwaynPlayer {
public:
void setActive();
void setConnected();
// ...
}
Now, things will be fine if AnnwaynPlayer has a virtual destructor. If it doesn't and your MyAnnwaynPlayer class has a non-trivial destructor then you have to wary of using an instance of MyAnnwaynPlayer through a pointer (be it raw or smart) of base class AnnwaynPlayer. When a pointer of the type is deleted, it will not chain through a call to your MyAnnwaynPlayer destructor.
Also consider ADL if you only need access to the public API of the base class. It's safer than inheritance, because you don't necessarily know the right class to inherit from in cases where the implementation returns something ultimately unspecified (like an internal derived class).
In essence, this would look like this:
namespace AnnwaynNamespace {
void setActive(AnnwaynPlayer& p);
void setConnected(AnnwaynPlayer& p);
};
And you could call them without using those functions (or the namespace), because ADL.
void wherever(AnnwaynNamespace::AnnwaynPlayer& p) {
setActive(p);
}
So setActive, etc, become part of the actual public API of the class, without involving any inheritance.

How to use inheritance for a class with TEST_CLASS in CppUnitTestFramework

I've got a class that inherits from another class like so:
class TestClass : public BaseClass
I am wondering if it is possible to make this a test class using the TEST_CLASS macro or some other macro that is part of the Microsoft Unit Testing Framework for C++. I tried:
class TEST_CLASS(TestClass : public BaseClass)
But the IDE gives the error 'Error: expected either a definition or a tag name' and the compiler error is error C3861: '__GetTestClassInfo': identifier not found
I know it's probably bad practice to inherit on a test class but it would make implementing the test easier. I am relatively new to C++ so I am wondering if it is something simple I have missed or if it's just not possible.
Thanks,
There is one other option you didn't include and others may be tripping over this question without knowing the solution.
You can actually derive from any arbitrary type by looking at the macro itself:
///////////////////////////////////////////////////////////////////////////////////////////
// Macro to define your test class.
// Note that you can only define your test class at namespace scope,
// otherwise the compiler will raise an error.
#define TEST_CLASS(className) \
ONLY_USED_AT_NAMESPACE_SCOPE class className : public ::Microsoft::VisualStudio::CppUnitTestFramework::TestClass<className>
As C++ supports multiple inheritance you can easily derive by using code similar to the following:
class ParentClass
{
public:
ParentClass();
virtual ~ParentClass();
};
TEST_CLASS(MyTestClass), public ParentClass
{
};
Just remember that if you are working with resources you will need to have a virtual destructor to have it be called. You will also have to call the initialize & cleanup methods directly if you are going to be using them, because the static methods they create are not called automagically.
Good luck, Good testing!
It's been a while since I used CppUnitTestFramework but back then this site has been a valuable resource for many questions on that topic.
TEST_CLASS is preprocessor macro. You can use it to declare a test class like
TEST_CLASS(className)
{
TEST_METHOD(methodName)
{
// test method body
}
// and so on
}
That's it. As far as I know there is no way to inherit test classes from one another.
Maybe though composition over inheritance might help in your specific case.