When to use static class functions instead of namespaced functions? - c++

I'm currently trying to implement a factory design pattern and somewhat confused as to how this is typically done in C++. I've been referring to this webpage.
So on that webpage, they show an example where they define a factory class called ComputerFactory. This class has a single NewComputer method which is static.
class ComputerFactory
{
public:
static Computer *NewComputer(const std::string &description)
{
if(description == "laptop")
return new Laptop;
if(description == "desktop")
return new Desktop;
return NULL;
}
};
The fact that NewComputer is static means it's not associated with a single instance of ComputerFactory. Thus it is possible to call this method from your code by writing
ComputerFactor::NewComputer("description");
Now I'm curious as to why this needed to be wrapped within a class. Because it's static and really isn't meant to be associated with any class, it would make more sense to do something like
namespace ComputerFactory
{
static Computer *NewComputer(const std::string &description)
{
if(description == "laptop")
return new Laptop;
if(description == "desktop")
return new Desktop;
return NULL;
}
}
So my questions:
Is the namespace function I described a valid alternative?
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
Now I believe there are instances where it would make sense to have static methods (e.g. static 'how many of these classes currently exist'), but this doesn't appear to be a situation where it's necessary. Any thoughts?
Edit: So I just had a thought, the example I listed isn't a 'typical' factory method. In practice, it's possible that the factory function is more complex and requires calling other functions (private class methods). In this case, it would make complete sense to wrap the factory into a class such that you could access subfunctions. Is this why factory methods are typically wrapped into classes?

Is the namespace function I described a valid alternative?
Yes
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
If the methods are utility methods that can be utilized in many classes, then it would make more sense for them to be in namespace.
If the methods are specific to the class then make them static inside the class itself, which would result in better encapsulation.

Is the namespace function I described a valid alternative?
Yes.
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
There are things you can do with a class that you cannot do with a namespace.
You mentioned one of them (to make use of private members, even though you can use an anonymous namespace to do something similar - not so good actually).
Another relevant example is that you cannot templatize a namespace and this can be quite annoying.
As an example, this happens with a class:
template<typename T>
struct S {
static T f() { return T(); }
// Other member functions
};
// ...
using MyS = S<int>;
MyS::f();
This happens with a template:
namespace N {
template<typename T>
T f() { return T(); }
// Other function template
}
// ...
N::f<int>();
In other terms, you can only define function template if you are using a namespace and it could not be the best solution in any situation.
Moreover, you cannot create an alias as you can do with your class, so you must be explicit about the types at any call place and it can be error-prone and difficult to refactor.

Related

Is it possible to override member access operators to detect when any member variable is modified?

Say I have:
struct foo{
int bar;
int baz;
...
bool flag;
}
Can an access operator -> or . be overridden to detect if bar or any other member variable is modified ?
EDIT:
The purpose is if I have many member variables and any of them is changed, I have a quick way of setting a flag, instead of using setters to encapsulate all the variables, making the code verbose.
Your approach is flawed because even if you override access operators you will not catch pointers writing the actual memory.
If most of the variables have the same type you can use an enum for flags and a single function to set or get a specific variable.
For example:
private:
int bar;
int baz;
public:
enum IntVariables { varBar, varBaz };
bool flag;
void setVariable(int varId, int value) {
flag = true;
if (varId == varBar)
bar = value;
else if (varId == varBaz)
baz = value;
}
I considered the following approach:
Just use a wrapper class that can have any data type, but implement all operations. In this same wrapper class override operators, and use the wrapper class in other class that require any modifications of member variables to be detected.
template <class T>
class wrapper {
private:
T var;
... .. ...
public:
T doSomethingToVar(T arg);
... .. ...
//Wherever the variable is modified send out a notification to whomever needs to detect the changes.
};
Pros:
When declaring variables in whichever class needs to detect modification of variables, it is easy to declare using the wrapper, without much additional code.
To ensure modifications are detected, need to implement functions / getters / setters / overload operators to detect modifications. This is tricky, and requires some thought.
Cons:
Tricky to implement a general purpose wrapper that can detect all modifications, since complex types can have functions that modify themselves in ways one is not aware of.
Notes:
How to ensure that every method of a class calls some other method first?
This answer is a work in progress, and I think it may be useful to others and maybe just cool to know about eventually, so open to comments. Will keep updating.
Update:
While writing out the above answer, I considered a different approach, of shifting responsibility onto the member variable classes:
class DetectChanges{
void onDetectChanges(){
//This function should be called by all implementing classes when the class has changes.
}
Can make it a design choice that all member variables inherit from DetectChanges.
The above two approaches are what I'm considering now. Not a solution yet, but thought I would put it out for comments and see if eventually we can figure something out.
}

c++ internal helper class

I would like to ask question regarding internal helper class in C++. What is the best way to structure this?
Let me clarify what do I mean by internal helper class by example.
// MyClass.h
class MyClass
{
int myData;
bool isSomething;
...
public:
void DoSomething();
};
// MyClass.cpp
// This is what I mean by internal helper function. Helper function that's only visible int the implementation file (.cpp) but requires access to the private members of the class.
static void DoSomethingInternal( MyClass *myClass )
{
// Access myClass private members
}
void MyClass::DoSomething()
{
...
DoSomethingInternal(this);
...
}
I know that declaring friend function can be a solution. However, it makes the class declaration ugly. In addition, for every new helper function, I have to add a friend function.
Is there an idiom/design pattern for this? I have been searching in the Internet, but didn't find any.
Thank you in advance. Your answers are greatly appreciated.
In my experience, a lot of dev teams have no problem with static local helper functions, it helps reduce header bloat, helps keep the formally exposed interface smaller, and so forth. It has the advantage of being lightweight, it has the disadvantage that it can lead to friend bloat/pollution if you are using lots of private members and no accessors.
But within the discussion community it is generally frowned upon in favor of the following.
Declaring helpers as private member functions.
This has the advantage of clearly associating fn _doThingsForFoo(Foo*) with Foo, and saving you from a lot of headaches exposing private members.
It has the downside of basically showing your underwear to everyone who needs to #include your header.
Using the Pimpl idiom.
You declare a second class, the "Private Implementation" (https://en.wikipedia.org/wiki/Opaque_pointer, Is the pImpl idiom really used in practice?) and you put all of the private stuff you don't want in the main header into that.
It has the advantage of allowing you to hide your stuff, it has the disadvantage of adding an extra pointer to feed, store and traverse (oh and free).
There are couple of ways to accomplish that.
Use a helper class/function in the .cpp file if the helper functions don't need access to the data directly. I would recommend this method ahead of the next method.
In the .cpp file:
// Create a namespace that is unique to the file
namespace MyClassNS
{
namespace HelperAPI
{
void DoSomethingInternal(MyClass* obj) { ... }
}
}
using namespace MyClassNS;
void MyClass::DoSomething()
{
...
//
HelperAPI::DoSomethingInternal(this);
...
}
Use the pimple idiom. When using this idiom, you can add any number of helper functions in the private data class without touching the public interface of the class.
The design pattern is simple: don't use helper classes. If a class should do something, let it do it itself.
As per the upvoted answer given by StenSoft, you should implement the methods inside the class. However, if that is not an option for some reason, then use helpers. If even that is not an option, then use reflection. If even that is not an option, then use a command listener inside your class. If even that is not an option, then watch a tutorial.
You can read these following sites for this purpose PIMPL, Opaque pointer. With this you only need to have one member variable and you can put all private things into the private class.
your header:
class PrivateClass;
class Class
{
public:
// ...
private:
PrivateClass* m_Private;
};
your source:
class PrivateClass
{
// ...
};
Class::Class
: m_Private( new PrivateClass )
{
// ...
}
UPDATE: I forgot to tell mention to delete the private member in the desctructor.
Class::~Class
{
delete m_Private;
// ...
}
// ...

Passing arbitrary data to a function without void pointers

I am working with an abstract base class implementing a set of system tests. In simplified form, the class declaration is:
class Test_Class
{
Test_Class();
~Test_Class();
Run_Test(void * param_set = NULL) = 0;
}
The base class requires the implementation of the Run_Test function which allows a user to pass in an arbitrary data structure as a void pointer and cast it to the appropriate type inside the body of Run_Test in a child class, in order to allow different tests to use different data structures, e.g. a float in one test vs a list of ints in another.
This is cumbersome and seems like an incredibly C-like way of doing things. Is there a better way of using inheritance or other language utilities?
Note: Due to customer constraints, this program is not allowed access to the STL or the Boost libraries.
Yes. User doesn't pass in an arbitary data structure but can make an arbitrary data structure by extending your base class.
class Test_Class {
Run_Test(const Config& config);
};
client code:
class MyConfig : public Config {
//...
};
Another option is templates. You can accomplish many common tasks with either, I'm not sure which is ideal in this situation so I'll leave it to other answers or to you to research that if you go this route.
If you want a set of tests, use std::vector<std::function<void()>> tests; and then you can simply tests.push_back([=] { do_test(the_args, I_captured, from_local, scope); });.
You can do similar tricks with std::bind if your compiler doesn't support lambdas.
There's no need for you, the end-user, to write your own generic function interface. It already has been done.
Edit: Yes, you're going to end up with some C-style garbage if you do not A) re-implement the wheels provided by Boost or the STL or B) use the existing wheels provided by Boost or STL. There is no magical third choice between "Write own good code" or "Use other people's good code" which still results in good code.
I dont remember is it possible/how to make argument detection for function inside class so maybe this will do:
class Test_Class {
public:
template <typename T>
void Run_Test(T p) {
}
};
template <class T>
void tester(Test_Class t, T p) {
t.Run_Test<T>(p);
}
int main() {
Test_Class p;
int a = 5;
tester(p, a);
}

Copying Methods from Member

I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.

C++ design with static methods

I would like to define as class X with a static method:
class X
{
static string get_type () {return "X";}
//other virtual methods
}
I would like to force classes which inherit from X to redefine the get_type() method
and return strings different from "X" (I am happy if they just redefine get_type for now).
How do I do this? I know that I cannot have virtual static methods.
Edit: The question is not about the type_id, but in general about a static method that
should be overriden. For example
class X {
static int getid() {return 1;}
}
template<int id>
class X {
public:
static int getid() { return id; }
};
class Y : public X<2> {
};
You haven't overridden the method, but you've forced every subclass to provide an ID. Caveat: I haven't tried this, there might be some subtle reason why it wouldn't work.
If I'm not mistaken, to call the static method, you have to invoke the method by specifying the exact name of the class, e.g X::get_type();, DerivedClass::get_type() etc and in any case, if called on an object, the dynamic type of the object is not taken into account. So at least in the particular case, it will probably only be useful in a templated context when you are not expecting polymorphic behavior.
However, I don't see why it shouldn't be possible to force each interesting class (inherited or not, since "compile-time polymorphism" doesn't care) to provide this functionality with templates. In the following case, you must specialize the get_type function or you'll have a compile-time error:
#include <string>
struct X {};
struct Derived: X {};
template <class T> std::string get_type() {
static_assert(sizeof(T) == 0, "get_type not specialized for given type");
return std::string();
}
template <> std::string get_type<X>() {
return "X";
}
int main() {
get_type<X>();
get_type<Derived>(); //error
}
(static_assert is C++0x, otherwise use your favourite implementation, e.g BOOST_STATIC_ASSERT. And if you feel bad about specializing functions, specialize a struct instead. And if you want to force an error if someone accidentally tries to specialize it for types not derived from X, then that should also be possible with type_traits.)
I'd say you know the why but just in case here's a good explanation:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/cplr139.htm
It looks like your going to have to design your way out of this. Perhaps a virtual function that wraps a Singleton?
Don't do that, use typeid instead.
To make a long story short, you can't do it. The only way to require a derived class to override a base class function is to make it a pure virtual (which can't be static).
You can't do this for a number of reasons. You can't define the function in X and have it be pure virtual. You can't have virtual static functions at all.
Why must they be static?
Here you go
class X
{
static string get_type() {return "X"; }
};
class Y : public X
{
static string get_type() {return "Y"; }
};
The code above does exactly what you requested: the derived class redefines get_type and returns a different string. If this is not what you want, you have to explain why. You have to explain what is it you are trying to do and what behavior you expect from that static method. If is absolutely unclear form your original question.
You mention a few places about guaranteeing that the child types yield unique values for your function. This is, as others have said, impossible at compile time [at least, without the use of templates, which might or might not be acceptable]. But if you delay it until runtime, you can maybe pull something similar off.
class Base {
static std::vector<std::pair<const std::type_info*, int> > datas;
typedef std::vector<std::pair<const std::type_info*, int> >::iterator iterator;
public:
virtual ~Base() { }
int Data() const {
const std::type_info& info = typeid(*this);
for(iterator i = datas.begin(); i != datas.end(); ++i)
if(*(i->first) == info) return i->second;
throw "Unregistered Type";
}
static bool RegisterClass(const Base& p, int data) {
const std::type_info& info = typeid(p);
for(iterator i = datas.begin(); i != datas.end(); ++i) {
if(i->second == data) {
if(*(i->first) != info) throw "Duplicate Data";
return true;
}
if(*(i->first) == info) throw "Reregistering";
}
datas.push_back(std::make_pair(&info, data));
return true;
}
};
std::vector<std::pair<const std::type_info*, int> > Base::datas;
class Derived : public Base { };
const DerivedRegisterFlag = Base::RegisterClass(Derived(), 10);
class OtherDerived : public Base { };
const OtherDerivedRegisterFlag = Base::RegisterClass(OtherDerived(), 10); //exception
Caveats: This is completely untested. The exceptions would get thrown before entering main if you do it this way. You could move the registration into constructors, and accept the per-instance overhead of registration checking if you'd rather.
I chose an unordered vector for simplicity; I'm not sure if type_info::before provides the necessary semantics to be used as a predicate for a map, and presumably you won't have so many derived classes that a linear search would be problematic anyhow. I store a pointer because you can't copy type_info objects directly. This is mostly safe, since the lifetime of the object returned by typeid is the entire program. There might be issues when the program is shutting down, I'm not sure.
I made no attempt to protect against static order of initialization errors. As written, this will fail at some point.
Finally, no it isn't static, but "static" and "virtual" don't really make sense together anyhow. If you don't have an instance of the type to act on, then how do you know which overwritten method to chose? There are a few cases with templates where you might legitimately want to call a static method without an actual object, but that's not likely to be common.
*edit: Also, I'm not sure how this interacts with dynamically linked libraries and the like. My suspicion is that RTTI is unreliable in those situations, so obviously this is similarly unreliable.
Use Delphi, it supports virtual static members on classes. ;>
Apologies for resurrecting this thread, but I've just encountered this moral crisis as well. This is a very bold and possibly foolish statement to make, but I wholeheartedly disagree with what most people are saying about static virtual not making any sense. This dilemma stems from how static members are commonly used versus what they're actually doing underneath.
People often express facts using static classes and/or members - something that is true for all instances if instances are relevant, or simply facts about the world in the case of static classes. Suppose you're modelling a Philosophy class. You might define abstract class Theory to represent a theory which is to be taught, then inherit from Theory in TheoryOfSelf, TheoryOfMind and so on. To teach a Theory, you'd really want a method called express() which expresses a theory using a particular turn of phrase appropriate to the audience. One would assume that any inheriting class should expose an identical method express(). If I were able to, I would model this relationship using static virtual Theory.express() - it is both a statement of fact transcending the concept of instances (therefore static) and nonspecific, requiring a specific implementation by each type of theory (therefore virtual).
I completely agree however with people justifying the prohibition on the grounds of what static is actually doing - it makes perfect sense in terms of coding principles, the issue arises from the customary ways people commonly model the real world.
The best resolution to this problem I've been able to think of is to model Theory as a singleton instead - there may be an instance of a theory, but there's only ever one of them. If you want an alternative, it's a different type, so create a new derived class. To me this approach just seems arbitrary and introduces unnecessary noise.