How safe and compiler-independent is this C++ code? - c++

I have created a bit of code that is strange to me, but seems to do what I want. However, I am not sure of its platform independence or how safe it is, or if there is a much easier way to do what I want.
I was reading on the Curiously Recurring Template Program (on wikipedia), and there was sample code for a class counter that lets each derived class keep track of how many instances have been created by inheriting from a base with that functionality.
I had been looking for ways to have derived classes reference to a common object (by pointer) without having to add a static variable and define a virtual function for each new class I create. (I was planing on creating quite a few derived classes.) But, the derived classes, because they were created with templates, were considered different from the base so they could not be implicitly converted to a base pointer.
Dynamic_cast and static_cast didn't work, so I tried reinterpret_cast, for fun, to see what behavior that had. It ended up showing the static variable from the base class, which isn't what I wanted, but it reminded me of a previous experience I had with statics and virtual functions (long story). I wrote a virtual function in the base class, and the virtual function reported the correct variable for the derived classes, polymorphic-ally.
It works, at least according to codepad.org, but I'm still not sure of its platform consistency or the safety of reinterpret_cast in this case. Can someone with more experience than I clarify exactly why this works?
Here is my code. It looks like the Wikipedia sample code because that's what it was originally.
#include <iostream>
using namespace std;
template <typename T>
class counter
{
public:
static int separateObject;
virtual void printStatic(){
cout << this->separateObject << endl;
}
};
template <typename T> int counter<T>::separateObject( 0 );
class X : public counter<X>
{
// ...
};
class Y : public counter<Y>
{
// ...
};
typedef counter<void*>* voidcounter;
int main(){
X* counterX = new X;
Y* counterY = new Y;
counterX->separateObject = 9001;
counterY->separateObject = 42;
cout << "Object Xs value is: " << counterX->separateObject << endl;
cout << "Object Ys value is: " << counterY->separateObject << endl;
voidcounter polycount = reinterpret_cast<voidcounter>(counterX);
polycount->printStatic();
polycount = reinterpret_cast<voidcounter>(counterY);
polycount->printStatic();
return 0;
}

I had been looking for ways to have derived classes reference to a common object
Then don't use CRTP. CRTP is for when you need all of the base types to NOT be common (which is what allows each type to have it's own counter). That's 100% exactly what it's for. If you want a shared common base, use a normal virtual base class. You can't use static_cast or dynamic_cast because they have no base in common. What you're doing with reinterpret_cast is incredibly unsafe, as it is undefined behavior.
class shared_counter_base {
virtual ~shared_counter_base(){}
virtual void printStatic()=0;
};
template <typename T>
class counter : shared_counter_base
{
public:
static int separateObject;
virtual void printStatic() {
cout << this->separateObject << endl;
}
};
template <typename T> int counter<T>::separateObject( 0 );
class X : public counter<X>
{
// ...
};
class Y : public counter<Y>
{
// ...
};
int main(){
X* counterX = new X;
Y* counterY = new Y;
counterX->separateObject = 9001;
counterY->separateObject = 42;
cout << "Object Xs value is: " << counterX->separateObject << endl;
cout << "Object Ys value is: " << counterY->separateObject << endl;
shared_counter_base polycount = counterX;
polycount->printStatic();
polycount = counterY;
polycount->printStatic();
return 0;
}

Related

Inheritance and templates instanciations with pointers to simulate "virtual data"

I have a hierarchy of classes:
class Base
{
public:
Base():a{5}{}
virtual ~Base(){};
int a;
};
class Derived : public Base
{
public:
Derived():b{10}{}
int b;
};
I then have a class template that operates on whatever type it is instanciated with:
template<typename T>
class DoStuff
{
public:
DoStuff():val{}{}
virtual ~DoStuff(){};
virtual void printDoStuff() = 0;
T getVal(){return val;};
private:
T val;
};
class DoStuffWithInt : public DoStuff<int>
{
public:
virtual void printDoStuff() override {cout << "val = " << getVal() << endl;}
};
class DoStuffWithBase : public DoStuff<Base>
{
public:
virtual void printDoStuff() {cout << "a = " << getVal().a << endl;}
};
Now I would like to have a hierarchy of class like this:
class DoStuffWithBase : public DoStuff<Base>
{
public:
virtual void printDoStuff() {printVal(); cout << "a = " << getVal().a << endl;}
};
// Wrong and will not compile, trying to make a point
class DoStuffWithDerived : public DoStuffWithBase<Derived>
{
public:
void printDoStuff() override {DoStuffWithBase::printDoStuff(); cout << "b = " << getVal().b << endl;}
};
Basically I would like to have DoStuffWithBase that operates on a base be extended so that I can reuse its functions, but the extended class DoStuffWithDerived should operate on a Derived type.
I managed to get something working by templating DoStuffWithBase with a pointer to Base and extending it:
template <class T>
static void deleteIfPointer(const T& t)
{
std::cout << "not pointer" << std::endl;
}
template <class T>
static void deleteIfPointer(T* t)
// ^
{
std::cout << "is pointer" << std::endl;
delete t;
}
template<typename T>
class DoStuff
{
public:
DoStuff():val{}{}
DoStuff(const T& value):val{value}{};
virtual ~DoStuff(){deleteIfPointer(val);}
virtual void printDoStuff() = 0;
T getVal(){return val;};
private:
T val;
};
class DoStuffWithBase : public DoStuff<Base*>
{
public:
// New base
DoStuffWithBase(): DoStuff(new Base()){}
DoStuffWithBase(Base* b) : DoStuff(b){}
virtual void printDoStuff() {printVal(); cout << "a = " << getVal()->a << endl;}
};
class DoStuffWithDerived : public DoStuffWithBase
{
public:
// New derived
DoStuffWithDerived(): DoStuffWithBase(new Derived()){}
void printDoStuff() override {DoStuffWithBase::printDoStuff(); cout << "b = " << static_cast<Derived*>(getVal())->b << endl;}
};
It works but there are several things I don't like:
The code is a lot more complicated, when 99% of the time, I won't need to extend a DoStuffWithX class, I will just use DoStuffWithInt, DoStuffWithClass, DoStuffWithAnotherClass etc... Here I had to add several constructors, a special case destructor and so on.
I have to use pointers and manage them (static_cast when needed, deletion...), all in order to avoid slicing and get the right type. Also, DoStuff::val should theorically not be null, but with a pointer there is no way I can prevent that (or atleast I don't know one). Maybe using smart pointers would help a bit here ? I am not super familiar with them.
I have to manage cases where T is a pointer and when it is not. For example, the deleteIfPointer function above, but also switching between . and -> and probably more.
Is there any simpler way to achieve what I am trying to do ? A design pattern or something else ? Am I stuck with my solution and is it somewhat good ?
Edit: I tried to implement it with std::variant as in #Tiger4Hire's answer:
class Derived : public Base
{
public:
Derived():b{10}{}
int b;
};
class Derived2 : public Base
{
public:
Derived2():c{12}{}
int c;
};
using DerivedTypes = std::variant<Derived, Derived2>;
struct VariantVisitor
{
void operator()(Derived& d)
{
d.b = 17;
}
void operator()(Derived2& d)
{
d.c = 17;
}
};
class DoStuffWithVariant : public DoStuff<DerivedTypes>
{
public:
void handleBasePart(Base& base)
{
cout << "a = " << base.a << endl;
base.a = 10;
}
virtual void printDoStuff() override
{
auto unionVal_l = getVal();
if (std::holds_alternative<Derived>(unionVal_l))
{
std::cout << "the variant holds a Derived!\n";
auto& derived_l = std::get<0>(unionVal_l);
cout << "b = " << derived_l.b << endl;
handleBasePart(derived_l);
}
else if (std::holds_alternative<Derived2>(unionVal_l))
{
std::cout << "the variant holds a Derived2!\n";
auto& derived2_l = std::get<1>(unionVal_l);
cout << "c = " << derived2_l.c << endl;
handleBasePart(derived2_l);
}
std::visit(VariantVisitor{}, unionVal_l);
}
};
What I like about it:
I don't have to use pointers.
I feel the code is less tricky, easier to understand.
What I don't like about it:
The code is all in one place and it deals with all the possible Derived types (and even the Base type) at once whereas with inheritance, classes are more specialized, you can really look at a class and directly know what it does, what it overrides etc... On the other hand one could argue that it means the algorithm is in one place instead of dispatched all over the classes hierarchy.
You can't have an abstract base class as your interface.
All in all it is a really good alternative, but I am still wondering if there is a simpler way to implement dynamic polymorphism ? Do you necessarily have to resort to (base class) pointers with dynamic polymorphism ? Are std::variant the way to go now ?
Edit2: 2 other drawbacks with variants that I didn't notice at first:
All your derived class and your base class have to be defined in the same library. Clients can't easily add a new Derived class since it would mean modifying the variant and they might not have access to it.
On the project I am working on, base classes are defined in one library, and are derived in other independant "sub" libraries. So if I try to use variant in my main library, it won't be able to access the Derived types in the sub libraries, which is a major issue.
If your base class implenting the variant (DoStuff here) has other members, when you call std::visit on the variant, you might have to also embark the needed other members of DoStuff. I think you should be able to use lambdas to capture them, but still, it's a lot less straightforward than using them directly as in the case of inheritance.
Your core problem is that you cast away your type information.
C++ will always call the right function, if it knows the correct type. This is why the pattern of pointer-to-base is almost always an anti-pattern (even though it is often taught as the "C++" way to do things).
Modern C++-style is to hold things as strongly-typed pointers, and cast them to the base pointer object, only when calling a function that takes a base-pointer as a parameter.
The standard supports this way of working by providing std::variant. Thus rather than
std::vector<Base*> my_list_of_things;
my_list_of_things.push_back(new Derived); // casting away type is bad
You start with
using DerivedTypes = std::variant<std::unique_ptr<Derived1>,
std::unique_ptr<Derived2>/*,etc*/>;
std::vector<DerivedTypes> my_list_of_things;
Now you can iterate over the list, calling a function which takes a pointer-to-base, casting away the type information only during the call.
You can also visit the members of the list, with a function (often a lambda) that knows exactly the type it is working on.
So you get the best of both worlds!
This does assume you have access to C++17 or above though, also that you are not working with code that is a library (compiled) but allows the library user to make their own classes. For example, libraries like Qt can't use this way of working.
If you don't have access to C++17, you may find curiously recursing templates fit much of what you are doing. (This is a controversial pattern though, as it is ugly and confusing)

Arrays of template class objects

Problem
I would like an array of pointers to instances of a template class. My problem would be solved if C++ allowed templated virtual methods in a base class, with a templated derived class.
Therefore, how would one implement templated virtual methods?
Below I have a solution which seems to work, but I'm interested in comments about my implementation.
Constraints
The template parameter is infinitely variable, e.g., I cannot enumerate every specialization of this template class. The template class T can be any POD, array of POD, or struct of POD.
The complete set of T is known at compile time. Basically, I have a file which defines all the different T used to instantiate the objects, and use Xmacros (https://en.wikipedia.org/wiki/X_Macro) to create the array of objects.
I know this isn't a great idea. Let's gloss over that for the time being. This ends up being more a curiosity.
Possible Solutions
These are the things I've looked into.
Create base and derived classes
class Base {
virtual void SomeMethod() = 0;
}
template <class T>
class Derived : Base {
void SomeMethod() {...}
}
The problem with this is I cannot declare all the virtual methods in Base that I want to overload, as virtual methods cannot be templated. Otherwise, it would be a perfect solution.
std::any/std::variant
I am using C++17, so I could define the virtual base methods taking std::any. But it cannot hold arrays, which precludes its use here.
CRTP
It seems this would not help me create an array of these different objects. I would need to do something like
template <typename D, typename T>
class Base
{
...
};
template <typename T>
class Derived : public Base<Derived, T>
{
...
};
So I still end up with trying to create an array of Derived<T> objects.
Visitor Pattern
Again it looks like I would need to enumerate every possible type the Visitable class needs to service, which, while not impossible (again, I have a file which defines all the different T that will be used) seems like more Xmacros, which is just making the problem more complicated.
My Solution
This is what I came up with. It will run in https://www.onlinegdb.com/online_c++_compiler
#include <iostream>
#include <array>
#include <typeinfo>
// Base class which declares "overloaded" methods without implementation
class Base {
public:
template <class T>
void Set(T inval);
template <class T>
void Get(T* retval);
virtual void Print() = 0;
};
// Template class which implements the overloaded methods
template <class T>
class Derived : public Base {
public:
void Set(T inval) {
storage = inval;
}
void Get(T* retval) {
*retval = storage;
}
void Print() {
std::cout << "This variable is type " << typeid(T).name() <<
", value: " << storage << std::endl;
}
private:
T storage = {};
};
// Manually pointing base overloads to template methods
template <class T> void Base::Set(T inval) {
static_cast<Derived<T>*>(this)->Set(inval);
}
template <class T> void Base::Get(T* retval) {
std::cout << "CALLED THROUGH BASE!" << std::endl;
static_cast<Derived<T>*>(this)->Get(retval);
}
int main()
{
// Two new objects
Derived<int>* ptr_int = new Derived<int>();
Derived<double>* ptr_dbl = new Derived<double>();
// Base pointer array
std::array<Base*, 2> ptr_arr;
ptr_arr[0] = ptr_int;
ptr_arr[1] = ptr_dbl;
// Load values into objects through calls to Base methods
ptr_arr[0]->Set(3);
ptr_arr[1]->Set(3.14);
// Call true virtual Print() method
for (auto& ptr : ptr_arr) ptr->Print();
// Read out the values
int var_int;
double var_dbl;
std::cout << "First calling Get() method through true pointer." << std::endl;
ptr_int->Get(&var_int);
ptr_dbl->Get(&var_dbl);
std::cout << "Direct values: " << var_int << ", " << var_dbl << std::endl;
std::cout << "Now calling Get() method through base pointer." << std::endl;
ptr_arr[0]->Get(&var_int);
ptr_arr[1]->Get(&var_dbl);
std::cout << "Base values: " << var_int << ", " << var_dbl << std::endl;
return 0;
}
When this is run, it shows that calling the methods on Base correctly point to the Derived implementations.
This variable is type i, value: 3
This variable is type d, value: 3.14
First calling Get() method through true pointer.
Direct values: 3, 3.14
Now calling Get() method through base pointer.
CALLED THROUGH BASE!
CALLED THROUGH BASE!
Base values: 3, 3.14
Essentially I am manually creating the virtual method pointers. But, since I am explicitly doing so, I am allowed to use template methods in Base which point to the methods in Derived. It is more prone to error, as for example for each template method I need to type the method name twice, i.e., I could mess up:
template <class T> void Base::BLAH_SOMETHING(T inval) {
static_cast<Derived<T>*>(this)->WHOOPS_WRONG_CALL(inval);
}
So after all this, is this a terrible idea? To me it seems to achieve my objective of circumventing the limitation of templated virtual methods. Is there something really wrong with this? I understand there could be ways to structure the code that make all this unnecessary, I am just focusing on this specific construction.
It is more prone to error, as for example for each template method I need to type the method name twice
Oh, that's the least of your concerns. Imagine if you downcast to the wrong type.
At least save yourself a headache and use dynamic_cast:
class Base {
public:
virtual ~Base() = default;
template <class T>
void Set(T inval) {
dynamic_cast<Derived<T>&>(*this).Set(inval);
}
template <class T>
T Get() {
return dynamic_cast<Derived<T>&>(*this).Get();
}
};
template <class T>
class Derived : public Base {
public:
void Set(T inval) {
storage = inval;
}
T Get() {
return storage;
}
private:
T storage{};
};
Other than that, I agree with the comments, this is probably not the right approach to your problem.
The normal run-off-the-mill method of dealing with subclasses that contain unknown types is to move the entire thing to a virtual function. Thus, instead of
superclass->get_value(&variable_of_unknown_type);
print(variable_of_unknown_type);
you write
superclass->print_value();
Now you don't need to know about any of the types a subclass might contain.
This is not always appropriate though, because there could be lots of operations. Making every operation a virtual function is troublesome if you are adding new operations all the time. On the other hand, the set of possible subclasses is often limited. In this case your best bet is the Visitor. Visitor rotates the inheritance hierarchy 90°, so to speak. Instead of fixing the set of operations and adding new subclasses freely, you fix the set of subclasses and add new operations freely. So instead of
superclass->print_value();
you write
class PrinterVisitor : public MyVisitor
{
virtual void processSubclass1(Subclass1* s) { print(s->double_value); }
virtual void processSubclass2(Subclass2* s) { print(s->int_value); }
};
superclass->accept(PrinterVisitor());
Now accept is the only virtual function in your base class. Note there are no casts that could possibly fail anywhere in the code.

Corrupt member variable in derived class with Curiously Recurring Templating Pattern

I'm currently playing around with CRTP and am coming across the issue of a member variable in the derived class being corrupted aka having a garbage value (there are currently 4 levels of polymorphism, with the top most base class called "A" and the bottom most derived class called "D").
Here is some code that displays an example of this issue:
//A.hpp
template <class TB>
class A {
public:
A();
void CRTP_func();
};
template <class TB>
A<TB>::A() {
std::cout << "A constructor called!" << std::endl;
}
template<class TB>
void A<TB>::CRTP_func() {
std::cout << "CRTP_index called in A" << std::endl;
static_cast<TB*>(this)->CRTP_func2();
}
//B.hpp
#include "A.hpp"
#include <vector>
template<class TC>
class B : public A<B<TC>>
{
public:
B();
void CRTP_func2();
};
template<class TC>
B<TC>::B() {
std::cout << "B constructor called!" << std::endl;
}
template<class TC>
void B<TC>::CRTP_func2() {
std::cout << "CRTP_func called in B" << std::endl;
static_cast<TC*>(this)->CRTP_func3();
}
//C.hpp
#include "B.hpp"
template<class TD>
class C : B<C<TD>> {
public:
C();
void CRTP_func3();
int x;
};
template<class TD>
C<TD>::C() {
std::cout << "C constructor called" << std::endl;
}
template<class TD>
void C<TD>::CRTP_func3() {
std::cout << "CRTP_index3 called in C" << std::endl;
static_cast<TD*>(this)->CRTP_func4();
}
//D.hpp
#include "C.hpp"
class D : C<D> {
public:
D();
bool onInit();
void CRTP_func4();
C<D> top;
int y = 0;
};
D::D() {
std::cout << "D constructor called!" << std::endl;
}
bool D::onInit() {
std::cout << "D onInit called!" << std::endl;
y = 5;
return true;
}
void D::CRTP_func4() {
std::cout << y << std::endl;
std::cout << "CRTP_index4 called in D! " << std::endl;
}
//main.hpp
int main {
D * D_ptr = new D();
D_ptr->onInit();
D_ptr->top.CRTP_func3();
return 0;
}
As you can see A is the base class while D is the derived class as such:
A<B<C<D>>>
The output for this program is as follows:
A constructor called!
B constructor called!
C constructor called
A constructor called!
B constructor called!
C constructor called
D constructor called!
D onInit called!
CRTP_index3 called in C
-33686019
CRTP_index4 called in D!
The value -33686019 is printed out in D.hpp where the value y is printed and is set to 5 upon initialization. After a little digging I checked the value in main.cpp and it is set to 5 even after making these CRTP calls, yet a garbage value gets printed.
After some more debugging I realized that removing the line
int x;
in B.hpp solves this problem, so I think the issue has to do with some misalignment, but I am not sure why this would happen. Does anyone know why this would happen or how to fix it?
Sorry for the long post and ambiguous code, I tried to remove most of the complexity and simplify the code as much as possible for the sake of the post.
UPDATE:
Thanks to the comments below I figured out how to fix my issue. Instead of using D::top, a better approach is to create a pointer in the main file as such:
C<D> * C_ptr = static_cast<C<D>*>(D_ptr);
and then call CRTP_func3() from there as such:
C_ptr->CRTP_func3();
This works as intended.
You call the function CRTP_func3() on an object with static type C<D> (D::top). The function C<D>::CRTP_func3() does a static_cast<D*>(this) but the object doesn't have the expected type. Thus, the behavior is undefined.
The most fundamental problem you have, logic-wise, is that you are expecting D_Ptr and D_Ptr->top to have the same value for y (you said you expected 5). D_Ptr->top is an entirely different instance and even if it ultimately derived from D, would have its own copy of y.
Then, D derives from C, so it's fundamentally impossible for a C to derive from D, regardless of template insanity. That's the assumption you make by calling CRTP_func4 on a this pointer of C.
Furthermore, that same function call assumes the template type TD is an instance of D. That function call exists within C, and that's an insane assumption for C to make--although I believe it happens to be correct in this case. (that one the compiler would catch if it weren't)
Lastly regarding crtp: consider rejecting Satan and all his ways.
But seriously, there's obviously no complete stand-in, but I think you'll find if you fully consider the power of interfaces (or pure abstract classes in C++), you may be able to find a way around using it. And have (nearly) the same performance... I don't know your specific problem, of course, but I'd highly recommend taking a long, careful look at this article https://en.wikipedia.org/wiki/Composition_over_inheritance
Particularly look at the 2nd example code block, that's written in C# (where interface would be a pure abstract class in C++). Give some thought to whether this pattern could help you.

Is there any use for a class to contain only (by default) private members in c++?

Members of a class are by default private in c++.
Hence, I wonder whether there is any possible use of creating a class that has all its members (variables and functions) set by default to private.
In other words, does there exist any meaningful class definition without any of the keywords public, protected or private?
There is a pattern, used for access protection, based on that kind of class: sometimes it's called passkey pattern (see also clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) and How to name this key-oriented access-protection pattern?).
Only a friend of the key class has access to protectedMethod():
// All members set by default to private
class PassKey { friend class Foo; PassKey() {} };
class Bar
{
public:
void protectedMethod(PassKey);
};
class Foo
{
void do_stuff(Bar& b)
{
b.protectedMethod(PassKey()); // works, Foo is friend of PassKey
}
};
class Baz
{
void do_stuff(Bar& b)
{
b.protectedMethod(PassKey()); // error, PassKey() is private
}
};
Tag dispatching. It's used in the standard library for iterator category tags, in order to select algorithms which may be more efficient with certain iterator categories. For example, std::distance may be implemented something like this: (in fact it is implemented almost exactly like this in gnu libstdc++, but I've modified it slightly to improve readability)
template<typename Iterator>
typename iterator_traits<Iterator>::difference_type
distance(Iterator first, Iterator last)
{
return __distance(first, last,
typename iterator_traits<Iterator>::iterator_category());
}
Where __distance is a function which is overloaded to behave more efficiently for std::random_access_iterator_tag (which is an empty struct, but could just as easily be a class), simply using last - first instead of the default behavior of counting how many increments it takes to get first to last.
Application wide resource acquisition ?
#include <iostream>
class C {
C() {
std::cout << "Acquire resource" << std::endl;
}
~C() {
std::cout << "Release resource" << std::endl;
}
static C c;
};
C C::c;
int main() {
return 0;
}
As stated in comments below, I have I mind an industrial application that had to "lock" some hardware device while the program was running. But one might probably found other use for this as, after all, it is only some "degenerated" case or RAII.
As about using "private" methods outside the declaration block: I use a static member here. So, it is declared at a point where private members are accessible. You're not limited to constructor/destructor. You can even (ab)use a static methods and then invoke private instance methods using a fluent interface:
class C {
C() { std::cout << "Ctor " << this << std::endl; }
~C() { std::cout << "Dtor" << this << std::endl; }
static C* init(const char* mode) {
static C theC;
std::cout << "Init " << mode << std::endl;
return &theC;
}
C* doThis() {
std::cout << "doThis " << std::endl;
return this;
}
C* doThat() {
std::cout << "doThat " << std::endl;
return this;
}
static C *c;
};
C *C::c = C::init("XYZ")
->doThis()
->doThat();
int main() {
std::cout << "Running " << std::endl;
return 0;
}
That code is still valid (as all C members are accessible at the point of declaration of C::c). And will produce something like that:
Ctor 0x601430
Init XYZ
doThis
doThat
Running
Dtor0x601430
Meaningful? Good practice? Probably not, but here goes:
class DataContainer {
friend class DataUser;
int someDataYouShouldNotWorryAbout;
};
class DataUser {
public:
DataUser() {
container.someDataYouShouldNotWorryAbout = 42;
}
private:
DataContainer container;
};
No, there is no sense in creating a class without public member variable and/or functions, since there wouldn't be a way to access anything in the class. Even if not explicitly stated, the inheritance is private as well.
Sure, you could use friend as suggested, but it would create unneeded convolution.
On the other hand, if you use struct and not class to define a class, then you get everything public. That may make sense.
For example :
struct MyHwMap {
unsigned int field1 : 16;
unsigned int field2 : 8;
unsigned int fieldA : 24;
};
An admittedly ugly case from many, many years ago and not in C++ but the idea would still apply:
There was a bug in the runtime library. Actually fixing the offending code would cause other problems so I wrote a routine that found the offending piece of code and replaced it with a version that worked. The original incarnation had no interface at all beyond it's creation.
A derived class can be all-private, even its virtual methods redefining/implementing base-class methods.
To construct instances you can have friend classes or functions (e.g. factory), and/or register the class/instance in a registry.
An example of this might be classes representing "modules" in a library. E.g. wxWidgets has something like that (they are registered and do init/deinit).

Creation of objects only in Manager class

I want to create a manager class which shall manage all the created objects of one type. Naturally this class should also create these objects. Therefore the client isn't allowed to create objects by himself, but instead must always use the manager class to do it.
Additionally the client is allowed to define his own classes which will be managed by one Manager.
template<class Type>
class Manager{
//...
Type* createInstance(){
Type* ptr = new Type();
//do sommething
return ptr;
}
};
The problem is: How do I restrict the creation of instances only to the manager class?
One possibility would be to declare the constructor as private and the Manager class as a friend class:
class A{
friend class Manager<A>;
private:
A(){}
~A(){}
};
Since the client is allowed to define own classes he could just declare the constructor public and the manager would still work without any problems. But the client would be able to create instances of those classes without the manager class witnessing it, resulting in bad behaviour/ressource management of the framework.
Is there a way to overcome this problem?
Managers of this sort are usually a bad pattern. The following code sample shows why.
It's the same problem as the one that says all destructors should be virtual. I use Manager to create a B, which derives from A, assign the object into an A* pointer. If it's destroyed as such, it goes through Manager::destroy(), which will probably not end well since it was created via Manager::make()
#include <iostream>
using namespace std;
template<class Type>
class Manager
{
public:
Manager(char *type)
{
mytype = type;
}
Type *make()
{
Type *ptr = new Type();
cout << "in Manager<" << mytype << ">::make() ptr->mytype is " << ptr->mytype << endl;
return ptr;
}
void destroy(Type *ptr)
{
cout << "in Manager<" << mytype << ">::destroy() ptr->mytype is " << ptr->mytype << endl;
delete ptr;
}
private:
char *mytype;
};
class A
{
friend class Manager<A>;
protected:
A()
{
mytype = "A";
cout << "in A()" << endl;
}
virtual ~A()
{
cout << "in ~A() mytype is " << mytype << endl;
}
char *mytype;
};
class B : public A
{
friend class Manager<B>;
protected:
B()
{
mytype = "B";
cout << "in B()" << endl;
}
virtual ~B()
{
cout << "in ~B() mytype is " << mytype << endl;
}
};
int main()
{
Manager<A> ma("A");
Manager<B> mb("B");
B *b = mb.make();
A *a = b;
ma.destroy(a); // This line calls Manager<A>::destroy. It should call Manager<B>::destroy.
return 0;
}
which produces the following as output:
in A()
in B()
in Manager<B>::make() ptr->mytype is B
in Manager<A>::destroy() ptr->mytype is B -- Oops - wrong destroy.
in ~B() mytype is B
in ~A() mytype is B
Which in turn means you can't use inheritance to it's full capability, which really defeats the purpose of using an OO language in the first place.
Depending on why you think you need a manager, there is probably a better solution.
If it's for memory management (unlikely given your original code snippet), overriding new and delete is worth taking a look at.
If it's for keeping track of all instances for processing purposes (e.g. objects in a game that get updated every game tick) then while it's a bit of a mental gearshift, a better solution is to integrate the manager into the class itself, as a set of static member functions and variables. Managers of this sort are almost invariably singletons, so making them static members / functions gets you to the same place semantically.
So you might have:
static set<A *> s_collection;
static void Heartbeat() // in class A
{
// lock s_collection here
for (auto it = s_collection.begin, end = s_collection.end() it != end; ++it)
{
// process *it
}
// unlock s_collection here
}
and then during A::A() you insert this into s_collection, and likewise during A::~A() you erase this.
Just be careful to use suitable synchronization primitives if you're multithreaded since most stl containers are not inherently thread safe.
You could use some variation of the passkey pattern to achieve this:
http://coliru.stacked-crooked.com/a/257860767a74a15e