A few questions about C++ classes - c++

I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:
someclass class; <----object construction
class.somefunction();
Is there a way just to call the function with the object construction?
And the second question is it okay to put multiple small classes in one header file?

Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):
// Global function
void foo() { /* do something */ }
// Static function
class Foo
{
public:
static void foo() { /* do something */ }
};
For your second question, yes it's ok. Generally people stick to one class per file, but in my opinion there's nothing wrong with having a few small classes in a single file.

If your function is declared static then you don't need an object instance to call it.
class Foo
{
public:
static void Bar() {}
};
// ...later
Foo::Bar();
To answer your second question, yes it's sometimes ok. I've done that before with small utility structs that are related to each other. Usually I'm just being lazy and don't want to bother making separate files.

Is there a way just to call the function with the object construction?
Only if the function is declared static. (ok, that's a lie, its possible without constucting a object if you subvert the type system, but it's not a good idea)
And the second question is it okay to put multiple small classes in one header file?
Sure, it's done all of the time.

1 static as already mentioned
2 do what feels natural. Keep related classes together. One of the problems with JAva is its fanatical enforcement of one class per file
However - unforgivable sin is spreading the implementation of class a throughout the implementations of classes b c and d
Ie all of a class implementation should be in one .cpp file.

delcare the function as static.
Are you talking about inner classes? If thats the case, then its totally legit.

Related

static inline in class inheritance

I am reading some of the Epic Games UnrealEngine4 source code and see couple of practices which make me wonder if I miss some of essential C++ magic.
static inline member methods in class declaration.Here #dividebyzero user actually sheds very important info regarding the effect of using static inline,at least with GCC compiler - inline placement similar to how MACRO functions behave.
Another interesting practice I can see is how UE4 creates interfaces for inheritance.Here is example based on how OpenGL backend module in UE4 looks like:
class FOpenGLBase
{
public:
static FORCEINLINE void UnmapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize) UGL_REQUIRED_VOID
};
Where UGL_REQURED_VOID is replaced with default function body,which reports "unimplemented" method error if called on this base class.
Next come inheritance of the above class:
struct FOpenGL3 : public FOpenGLBase
{
static FORCEINLINE void UnmapBuffer(GLenum Type)
{
glUnmapBuffer(Type);
}
static FORCEINLINE void UnmapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize)
{
UnmapBuffer(Type);
}
};
I even didn't know it was possible for a struct to inherit from class and vice -versa.
I understand that static + inline makes it possible to generate unique function body per function call,which makes it possible to put different body but with same signature in subclass's declaration.
But then I also wonder why one needs virtual inheritance for small methods if it is possible to override static inline methods in subclass just like this?
Why such an approach is not common? (at least from my experience I find it uncommon)
PS: I wasn't sure if this question format is ok for SO or should be rather put in CodeReview site.
First of all, the post you refer to seems to be about static inline functions in the namespace scope. Your example has them in a class scope. There's a very big difference between these two scopes.
In class scope, the static keyword makes the method callable on the class, instead of on an instance. So in this scope, there's a very real difference between static, static inline and just inline.
Next, static methods in class scopes have nothing to do with inheritance, exactly because static members are part of the class rather than instances. Inheritance is only relevant for instances. To make this clear, consider how you would call UnmapBufferRange on either FOpenGLBase or FOpenGL3:
FOpenGLBase::UnmapBufferRange(..); // Call the FOpenGLBase version
FOpenGL3::UnmapBufferRange(..); // Call the FOpenGL3 version
There's no inheritance because you couldn't even override it - you simply redefine it for another class. This effectively hides it, so it looks like inheritance but it's not the same!

Sharing function between classes

I have three classes which each store their own array of double values. To populate the arrays I use a fairly complex function, lets say foo(), which takes in several parameters and calculates the appropriate values for the array.
Each of my three classes uses the same function with only minor adjustments (i.e. the input parameters vary slightly). Each of the classes is actually quite similar although they each perform separate logic when retrieving the values of the array.
So I am wondering how should I 'share' the function so that all classes can use it, without having to duplicate the code?
I was thinking of creating a base class which contained the function foo() and a virtual get() method. My three classes could then inherit this base class. Alternatively, I was also thinking perhaps a global function was the way to go? maybe putting the function into a namespace?
If the classes have nothing in common besides this foo() function, it is silly to put it in a base class; make it a free function instead. C++ is not Java.
Declaring of a function in base class sounds the most appropriate solution. Not sure if you need virtual "get" though, instead just declare the array in the base class and provide access method(s) for descendants.
More complex part is "the input parameters vary slightly". If parameters differ by type only then you may write a template function. If difference is more significant than the only solution I see is splitting main function into several logic blocks and using these blocks in descendant classes to perform final result.
If your classes are quite similar, you could create a template class with three different implementations that has the function foo<T>()
Implement that function in base class. If these classes are similar as you say, they should be derived from one base class anyway! If there are several functions like foo(), it might be reasonable in some cases to combine them into another class which is utilized by/with your classes.
If the underlying data of the class is the same (Array of doubles), considering using a single class and overloading the constructor, or just use 3 different functions:
void PopulateFromString(const string&)
void PopulateFromXml(...)
void PopulateFromInteger(...)
If the data or the behavior is different in each class type, then your solution of base class is good.
You can also define a function in the same namespace as your classes as utility function, if it has nothing to do with specific class behavior (Polymorphism). Bjarne StroupStroup recommends this method by the way.
For the purpose of this answer, I am assuming the classes you have are not common in any other outwards way; they may load the same data, but they are providing different interfaces.
There are two possible situations here, and you haven't told us which one it is. It could be more like
void foo(double* arr, size_t size) {
// Some specific code (that probably just does some preparation)
// Lots of generic code
// ...
// Some more specific code (cleanup?)
}
or something similar to
void foo(double* arr, size_t size) {
// generic_code();
// ...
// specific_code();
// generic_code();
// ...
}
In the first case, the generic code may very well be easy to put into a separate function, and then making a base class doesn't make much sense: you'll probably be inheriting from it privately, and you should prefer composition over private inheritance unless you have a good reason to. You could put the new function in its own class if it benefits from it, but it's not strictly necessary. Whether you put it in a namespace or not depends on how you're organising your code.
The second case is trickier, and in that case I would advise polymorphism. However, you don't seem to need runtime polymorphism for this, and so you could just as well do it compile-time. Using the fact that this is C++, you can use CRTP:
template<typename IMPL>
class MyBase {
void foo(double* arr, size_t size) {
// generic code
// ...
double importantResult = IMPL::DoALittleWork(/* args */);
// more generic code
// ...
}
};
class Derived : MyBase<Derived> {
static double DoALittleWork(/* params */) {
// My specific stuff
return result;
}
};
This gives you the benefit of code organisation and saves you some virtual functions. On the other hand, it does make it slightly less clear what functions need to be implemented (although the error messages are not that bad).
I would only go with the second route if making a new function (possibly within a new class) would clearly be uglier. If you're parsing different formats as Andrey says, then having a parser object (that would be polymorphic) passed in would be even nicer as it would allow you to mock things with less trouble, but you haven't given enough details to say for sure.

How does this code create an instance of a class which has only a private constructor?

I'm working on a sound library (with OpenAL), and taking inspiration from the interface provided by FMOD, you can see the interface at this link.
I've provided some concepts like: Sound, Channel and ChannelGroup, as you can see through FMOD interface, all of those classes have a private constructor and, for example, if you would create a Sound you mast use the function createSound() provided by the System class (the same if you would create a Channel or a ChannelGroup).
I'd like to provide a similar mechanism, but I don't understand how it work behind. For example, how can the function createSound() create a new istance of a Sound? The constructor is private and from the Sound interface there aren't any static methods or friendship. Are used some patterns?
EDIT: Just to make OP's question clear, s/he is not asking how to create a instance of class with private constructor, The question is in the link posted, how is instance of classes created which have private constructor and NO static methods or friend functions.
Thanks.
Hard to say without seeing the source code. Seems however that FMOD is 100% C with global variables and with a bad "OOP" C++ wrapper around it.
Given the absence of source code and a few of the bad tricks that are played in the .h files may be the code is compiled using a different header file and then just happens to work (even if it's clearly non-standard) with the compilers they are using.
My guess is that the real (unpublished) source code for the C++ wrapper is defining a static method or alternatively if everything is indeed just global then the object is not really even created and tricks are being played to fool C++ object system to think there is indeed an object. Apparently all dispatching is static so this (while not formally legal) can happen to work anyway with C++ implementations I know.
Whatever they did it's quite ugly and non-conforming from a C++ point of view.
They never create any instances! The factory function is right there in the header
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system)
{ return FMOD_System_Create((FMOD_SYSTEM **)system); }
The pointer you pass in to get a System object is immediately cast to a pointer to a C struct declared in the fmod.h header.
As it is a class without any data members who can tell the difference?
struct Foo {
enum Type {
ALPHA,
BETA_X,
BETA_Y
};
Type type () const;
static Foo alpha (int i) {return Foo (ALPHA, i);}
static Foo beta (int i) {return Foo (i<0 ? BETA_X : BETA_Y, i);}
private:
Foo (Type, int);
};
create_alpha could have been a free function declared friend but that's just polluting the namespace.
I'm afraid I can't access that link but another way could be a factory pattern. I'm guessing a bit, now.
It is the factory pattern - as their comment says.
/*
FMOD System factory functions.
*/
inline FMOD_RESULT System_Create(System **system) { return FMOD_System_Create((FMOD_SYSTEM **)system); }
It's difficult to say exactly what is happening as they don't publish the source for the FMOD_System_Create method.
The factory pattern is a mechanism for creating an object but the (sub)class produced depends on the parameters of the factory call. http://en.wikipedia.org/wiki/Factory_method_pattern

Can I create functions without defining them in the header file?

Can I create a function inside a class without defining it in the header file of that class?
Why don't you try and see?
[˙ʇ,uɐɔ noʎ 'oᴎ]
Update: Just to reflect on the comments below, with the emphasis of the C++ language on smart compiling, the compiler needs to know the size of the class (thus requiring declaration of all member data) and the class interface (thus requiring all functions and types declaration).
If you want the flexibility of adding functions to the class without the need to change the class header then consider using the pimpl idiom. This will, however, cost you the extra dereference for each call or use of the function or data you added. There are various common reasons for implementing the pimpl:
to reduce compilation time, as this allows you to change the class without changing all the compilation units that depend on it (#include it)
to reduce coupling between a class' dependents and some often-changing implementation details of the class.
as Noah Roberts mentioned below the pimpl can also solve exception safety issues.
No. However, you can mimic such:
struct X
{
void f();
X();
~X();
private:
struct impl;
impl * pimpl;
};
// X.cpp
struct X::impl
{
void f()
{
private_function();
...
}
void private_function() { ...access private variables... }
};
//todo: constructor/destructor...
void X::f() { pimpl->f(); }
Short answer: No, you can't.
However, if you're trying to inject a private function into the class that will only be used in that class's implementation, you can create a function in an anonymous namespace within that class's .cpp file that takes an object of that type by reference or pointer.
Note that you won't be able to muck with the passed objects internal state directly (since there's no way for the class to declare friendship with that anonymous function), but if the function just aggregates operations from the public interface of the class it should work just fine.
No, you can't. It wouldn't make much sense anyway. How should users of your class that include the header file know about those functions and use them?
I have no idea what You are trying to do, but I have a strange gut feeling, that Pointer To Implementation (pImpl) idiom might be helpful. If you want to add a public method in a cpp file and that method is not declared in the class definition in a header, You can't do that and it doesn't make sense.

forward declare static function c++

I want to forward declare a static member function of a class in another file. What I WANT to do looks like this:
BigMassiveHeader.h:
class foo
{
static void init_foos();
}
Main.cpp:
class foo;
void foo::init_foos();
int main(char** argv, int argc)
{
foo::init_foos()
}
This fails out with "error C2027: use of undefined type 'foo'"
Is there a way to accomplish what I want to do with out making init_foos a free function, or including BigMassiveHeader.h? (BigMassiveHeader.h is noticeably effecting compile time, and is included everywhere.)
You cannot forward declare members of a class, regardless of whether they are static or not.
You can't forward declare members of your class but you could make a namespace and a function inside of that namespace and forward declare that.
namespace nsfoo
{
void init_foos();
}
Your class if needed could friend this function.
If you have a BigMassiveHeader, you should consider splitting it up into several SmallCompactHeaders. If you want to express that many classes and functions belong together semantically, you can put them in the same namespace. You can always provide a convenience-header that includes all your small headers.
You can't partially declare classes in C++, so either you'll have to put the class's declaration in its own, smaller header, or...
Include BigMassiveHeader.h in your file and use precompiled headers.
The Visual C++ way: http://msdn.microsoft.com/en-us/library/2yzw0wyd%28v=VS.71%29.aspx, or the GCC way: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html.
I know it's not the point of the question, but if BigMassiveHeader.h is not likely to change much over time, you should take a look at precompiled headers
As a first refactoring, I'd use a free function which calls the static function. It's not like your main method is getting called lots of times, so you won't notice an extra call, and that makes the least change to the existing code.
Of course, you don't actually say what you are trying to do, only what you want to do. If what you are trying to do is get init_foos called once on application start, use static object initialisation for that, rather than calling it in main. If what you are trying to do is get init_foos called after all static objects are created, then it's more complicated.
By static object initialisation, I mean something like having this in a .cpp file which has access to the definition of init_foos. Make it a friend and init_foos private to prevent multiple calls:
struct call_init_foos {
call_init_foos () { foo::init_foos(); }
} call_init_foos_on_startup;
to forward declaration of a single method of a class, you must declare the method as part of the class (as it really is).
for example, in your case, add to main.cpp:
class foo
{
public:
static void init_foos();
}
its not the prettiest, but it will save you having to include the whole header..
No, you need to include the header for that. Sorry.
Use a free function if you must, or split the class.