Access protected function from derived class - c++

I have the following typical scenario, in which I want to hide implementation details in a child class, and expose it through an interface:
template <typename Derived>
class Interface
{
public:
void a()
{
static_cast<Derived*>(this)->_a();
}
};
class Implementation : public Interface<Implementation>
{
protected:
void _a()
{
/*
...
*/
}
};
I think I understand why this doesn't work, and I know that declaring the class Interface as friend of Implementation solves it, but when it comes to more complex hierarchies, like multiple interfaces, and various levels of inheritance(as is my real case), things get really messy.
I would like to avoid having to declare friend class Interface<Implementation> in each class that implements an interface.
Is there an alternative nice-and-clean solution for this problem?
Thanks!

How about using virtual functions and polymorphism?
Create an object in your child class and reassign it to an interface class pointer or reference. Then create a pure virtual function in your interface class and define it in your child class.

Related

Prevent public uses of a class used as a private base class

How can ensure that only "my" code can use a class, even if it is used a base class? (If it's not used as a base class I can make it a private or protected nested class of one of my classes)
If I want to indicate that use of a base class for one of my classes is a mere implementation detail, I can use a private base class:
class Base
{
...
}
class Derived: private Base
{
public:
Derived(...): Base{...} {... };
...
}
To clients of my Derived class, that I used the Base class is not apparent:
#include "Derived.h"
void client() {
Derived d{...};
Base *b = static_cast< Base * >(&d);// error
...
}
But imagine that the Base class is so specialised, or confusing, or tricky to use, that I don't want it to be possible for clients of my code to use it as a base class or create objects of that class. I want it to be "private", in some sense, to some of my code, so client code like this fails:
#include "Derived.h"
class Client: Base// error wanted here
{
public:
Client(...): Base{...} {...};
...
}
void client()
{
Derived d{...};// OK
Base b{...};// error wanted here
Client c{...};// error wanted here
}
How can I do that?
In effect, I am asking how can I achieve something like Java's package-private classes, which are accessible to only other classes in the same "package" (module), but can not be used by code outside the "package".
You can "enforce" this by convention, by placing the "private" entities into a detail namespaces. Many popular libraries (e.g. Boost) do this:
namespace detail
{
class Base { /* ... */ };
}
class Derived : private detail::Base
{
/* ... */
};
When modules will be standardized this problem will be solved properly, as you will be able to control what entities get exported and which ones are implementation details.
This can't be done directly as you would do in Java. If it's only a matter of avoiding confusion you can move Base inside a namespace which is meant to be ignored by clients of your code, eg:
namespace hidden {
class Base {
..
};
}
class Derived : private hidden::Base {
...
};
If instead you really want to avoid the possibility of using Base then it's quite a difficult story if you plan to use Base as a parent of multiple classes (which amount could vary over time). You could give Base a private constructor, and indicate that each of your derived classes is a friend of Base:
class Hider {
private:
Hider() = delete;
class Base {
..
};
friend class Derived;
};
class Derived : Hider::Base {
..
};
Of course this requires manual maintenance for each new class you want to derive from Base.
If you want to enforce it 100%, and don't like the python method of" please don't use things that start with '_'" then I believe this is your port of call:
class Dave;
class MyPrivateBaseClasses {
private:
MyPrivateBaseClasses(); // ensure nothing can use this class
class BaseClassA {};
friend Dave;
};
class Dave : public/private MyPrivateBaseClasses::BaseClassA
{};
Sure - it means you have to friend everything that wants to use it, but it does give you exactly what you wanted; 100% protection against people using BaseClassA.

Non-Virtual Polymorphism in C++

I have developed the following code in an attempt to implement non-virtual polymorphism:
#include <functional>
#include <iostream>
namespace{
using std::function;
class base {
protected:
using signiture =void(void);
using func_t = function<signiture>;
~base(){}
public:
func_t bar;//std::function object to a function of type "signature"
};
}
template <typename implementation>
class foo:public base {
public:
foo(implementation* instance){
bar = func_t(std::bind(&implementation::bar_implementation,instance));
//binds a function of name "bar_implementation" from class implementation to the std::function object
//binds to object "instance"
}
};
typedef base foo_base;
class testcase:public foo<testcase> {
public:
friend class foo;//allows implementations to be protected or private
testcase():foo(this){}//sends instance to the constructor of the base class in order to enable binding
protected:
void bar_implementation(void){
std::cout<<"Hello"<<std::endl;
}
};
class testcase2:public foo<testcase2> {
public:
friend class foo;//allows implementations to be protected or private
testcase2():foo(this){}
protected:
void bar_implementation(void){
std::cout<<"World!"<<std::endl;
}
};
int main(int argc, const char * argv[]) {
testcase t;
testcase2 t2;
foo_base* b = &t;
foo_base* b2 = &t2;
b->bar();
b2->bar();
return 0;
}
In reality this code is spread out over a few files...
I would like to know if anything in my code can be considered bad-practice,undefined behavior or otherwise undesirable in some manor?
A Live Example
Any thoughts on this pattern as a replacement for virtual inheritance and the design are appreciated.
Let me know if i can clarify anything.
EDIT:
I am asking this question as an attempt to determine if there are any reasons why a design like this would be a suitable way to implement non virtual polymorphism and if it is not, why is that?
Your code is an interesting approach. It's a nice proof of concept but it has a major flaw: it doesn't manage inheritance consistently !
The problem : class inheritance
Suppose I want to create a class testcase22 which inherits from testcase2, but has its own implementation of bar().
Alternative 1: if I define it naively by inheriting from testcase2, it will use the bar_implementation of testcase2:
class testcase22:public testcase2 {
public:
testcase22() {} // naive contructor
protected:
void bar_implementation(void){ // will not be used
std::cout<<"Great!"<<std::endl;
}
};
Alternative 2: If I try to use your constructor pattern, it won't work because of a compiling error. Because the type deduction will use foo<testcase2>, which is not a direct base class of testcase22 and can hence not be used in the mem-initializer list:
class testcase22:public testcase2 {
public:
friend class foo;//allows implementations to be protected or private
testcase22():foo(this){} // !!!!! causes compile error
protected:
void bar_implementation(void){
std::cout<<"Great!"<<std::endl;
}
};
Alternative 3: if I'd use foo explicitly, it would not work because foo os not either a valid base type initializer.
Alternative 4: if I'd try to use multiple inheritance, I'd be confronted to ambiguous base class
class testcase22:public testcase2, public foo<testcase22> {
public:
friend class foo;//allows implementations to be protected or private
testcase22():foo(this){}
protected:
void bar_implementation(void){
std::cout<<"Great!"<<std::endl;
}
};
This could be solved by defining foo inheriting virtually from base:
class foo:public virtual base { ... };
Then it would compile, but it still would use the bar_implementation of testcase2 instead of that from testcase22. By the way, even if it would have worked, the virtual base would prevent possibility of using multiple inheritance with your class family.
Conclusion
Your nice construct works, but only with a single level of simple inheritance.
This is a major constraint. Especially when considering that the benefit of polymorphism is to manage natural hierarchies making best use of the inheritance relationships.
Your pattern is also relatively complex to use in comparison with easy to use virtual functions. What will your code look like with several polymorphic functions, some of them even overloaded ?
The goals you intend to achieve with your pattern is not clear, but honestly, I wouldn't go for this approach for real life projects that have to be maintained over several years. But this is my own subjective opinion of course.

C++ Storing child objects in a common container

I have a set of abstract parent classes in a namespace, similar to the following
namespace Core {
class Sparse;
class Dense;
}
I define those classes somewhere and after that I derive some child classes:
class SparseA: public Core::Sparse;
class SparseB: public Core::Sparse;
class DenseA: public Core::Dense;
Now I want to instantiate some objects of the child classes and store them in a common container that can be accessible from anywhere. How can I do this?
And another question: Should I include the child classes in the Core namespace aswell?
Thank you.
As long classes Sparse and Dense are unrelated, you can't store instances of derived classes in the same c++ standard container (unless you're going to use such fancy stuff as boost::variant or boost::any).
If you give them a common (abstract) base class you can use smart pointers ( e.g. std::unique_ptr<> or std::shared_ptr) to keep referencing them in a container (using the same pseudo syntax as in your sample)
namespace Core {
class CommonBase;
class Sparse : public CommonBase;
class Dense : public CommonBase;
}
typedef std::vector<std::unique_ptr<Core::CommonBase>> MyContainerType;
Another option might be a template wrapper class solution
namespace Core {
class WrapperBase {
public:
// Expose the common interface of Sparse and Dense as
// pure virtual functions
virtual void foo() = 0;
virtual ~WrapperBase() {}
};
template<class Impl>
class Wrapper : public WrapperBase {
private:
Impl& impl_;
public:
Wrapper(Impl& impl) : impl_(impl) {}
void foo() {
impl.foo(); // Delegate to the actual implementation
}
};
class Sparse;
class Dense;
}
typedef std::vector<std::unique_ptr<Core::WrapperBase>> MyContainerType;
MyContainerType container;
container.push_back(std::make_unique<Wrapper<SparseA>>());
container.push_back(std::make_unique<Wrapper<SparseB>>());
container.push_back(std::make_unique<Wrapper<DenseA>>());
The latter will allow to loosely couple classes like Sparse and Dense within a single container, but still at least requires some abstract interface, that could be be used behaviorally consistent for both classes, and classes derived from them.

c++ How do you call a templated base-class function from derived class instance

Found related questions but not the exact variant so I am posting a very simple question.
A derived class inherits from a templated base, and I want to call the base function, how to do it?
template <class A>
class testBase {
public:
void insert(const A& insertType) {
// whatever
}
};
class testDerived : testBase<double> {
// whatever
};
int main() {
testDerived B;
// Compiler doesn't recognize base class insert
// How do you do this?
B.insert(1.0);
}
Need public inheritance (default is private for class):
class testDerived : public testBase<double> {
A class has a default access level of 'private'. You basically inherited 'testBase' using private inheritance so that testBase's public interface is not part of testDerived's. Simple solution:
class testDerived: public testBase<double> {...};
I do wish C++ applied public inheritance by default though since that's generally a much more common case. Then again, we could just all use structs instead. :-D

Where to define functors used by many derived classes?

A common scenario in my code is that I got a functor that is used by many classes in a hierachy.
To make it accessible by all classes and stay DRY, I usually define it as a protected inner struct of my base class like that:
class Base
{
protected:
struct CommonFunctor
{
bool operator()()
{
return true;
}
};
};
class DerivedA : public Base
{
void FooA()
{
bool test = CommonFunctor()();
}
};
class DerivedB : public Base
{
void FooB()
{
bool test = CommonFunctor()();
}
};
I don't like that solution because it clutters my base class with many small functors, that are internal only and even if they are not accessible to the public, they decrease readability of my base class.
Do you know any other solutions for this scenario?
Just implement your functors in new files (BaseClassFunctors.cpp + BaseClassFunctors.h). Put them inside your namespace with an optional subnamespaces (e.g. namespace main.internal).
Now you include the header file in any derived classes you want, without cluttering the base class header.
As much as I (and, apparently, everyone else) hate multiple inheritance, it would come in handy here.
Just create a second class that contains all your functors and in your child classes derived from Base, inherit both Base and this new class.
You can just implement the functor elsewhere and still keep it as a member of the Base:
class Base
{
protected:
struct CommonFunctor;
};
struct Base::CommonFunctor
{
bool operator()()
{
return true;
}
};