Let's say I have a class Character: it holds many private variables such as positionX, PositionY, Atk, Def, Agi, Velocity and have to pass it to a function which processes and changes this Character variables.
Since it has so many variables, how do I pass these variables? Should I make getter and setter for each variable? What is the best practice regarding this?
I'm thinking about making a struct class that holds all those variables, so I can just pass that struct class, but I don't know if it's a good practice.
If you pass just the struct it will be copied. Good practice is to either pass it in as a reference or as a const reference, or even as a shared_ptr
void foo(const MyStruct& ms);
void foo(MyStruct& ms);
void foo(std::shared_ptr<MyStruct> ms);
If your function modifies private variables, then the function should probably be a member function.
If that is not appropriate, then you could declare the function a friend of the class.
If you have lots of functions that can't be members but need to access the member variables, and you don't need the encapsulation, then consider making the members public.
Related
Let's say that I have a function that gets called periodically. The function gets a value as parameter and I want to compare it to the value that was received during the earlier function call, ie. the value needs to be memorized. Should I use static non-member variable or a non-static member variable for that purpose? What are the advantages and disadvantages for both approaches?
As a static non-member approach I mean something like
class foo {
public:
void func(int value) {
static int lastValue;
if (value > lastValue) {
doSomething(value)
}
lastValue = value;
};
};
And as a non-static member variable something like
class foo {
private:
int lastValue_;
public:
void func(int value) {
if (value > lastValue_) {
doSomething(value)
}
lastValue_ = value;
};
};
Firstly, you should add some initialisation of the non-static lastValue_ member variable - as is you have undefined behaviour. (The static function-local variable will be initialised to 0, which may or may not suit you.)
What are the advantages and disadvantages for both approaches?
Using a non-static member variable means the program can create as many foo instances as they like, and they'll operate independently. No two threads should access the same foo object without synchronisation, but they can access foo instances that other threads aren't accessing, including any thread specific foo instances.
Having a non-static member variable can also make things easier to unit- and regression-test, as simply creating a new object will "reset" the state, whereas with a static function-local variable there's no easy way to restore the starting value (you have to hack in a function argument that requests that).
The function-local static variable does have the advantage of being more localised in the sense of accessibility from other code, making it clear it's only relevant to the func function. Using the tightest possible variable scope is normally desirable, but here this is massively less important than the points above.
More generally - in many ways the function-local static variable has the same issues as global variables or singletons - google will turn those up pretty smartly.
Sort of a style question here. Say I have a class A which has to do a sequence of reasonably complex things to its member variable B b
class A {
public:
void DoStuffOnB(){
DoThing1();
DoThing2();
DoThing3();
}
private:
B b;
void DoThing1(){ /* modify b */ }
void DoThing2(){ /* modify b */ }
void DoThing3(){ /* modify b */ }
};
where the DoThings functions only depend on b (or other member variables and some passed parameters). If I want to make those functions re-usable in the future outside of that class, I'm better off writing them as:
class A {
public:
void DoStuffOnB(){
DoThing1(b);
DoThing2(b);
DoThing3(b);
}
private:
B b;
void DoThing1(B& b){ /* modify b */ }
void DoThing2(B& b){ /* modify b */ }
void DoThing3(B& b){ /* modify b */ }
};
and then my DoThing functions can just be copied elsewhere in the future. Am I better off writing the function to take all relevant parameters like that, or should the function only take non-member parameters?
In case the answer is "you should write the function to take all relevant parameters", why would one bother to put it in a class?
When should you use a free function, and when should you use a member function?
Assuming from the context that the "do something on B" functions only operate on the B member and not other state in A then:
If the functions directly manipulate/operate on the private state of B then they should be members of B.
Else they should be free functions.
A member function is a member function because its' scope has access to the member variables without having to use referencing and pointer syntax. As someone mentioned earlier this would most likely make it simpler to code and maintain so you would use this method unless you needed the function to be a free function that might take the same type data but from different classes in which case you would have to pass by reference or use pointers to gain access to the scope of the variable.
Should you pass member variables within member functions?
There is no need to pass member variables to member functions, since the member functions have access to all the data members.
It's similar to free standing functions accessing static file local variables. The functions have access to the statically declared variables in the same translation unit.
When should you use a freestanding function and when should you use a member function?
In general, use a member function when the functionality is associated with the object.
Use a freestanding function when
the class has static members
or functionality is associated with a class and doesn't use static
members.
You can also use freestanding functions when the same functionality can apply to different objects.
For example, let's talk serialization or outputting of an object.
One can define a method, load_from_buffer() in an object, but it won't work with POD types.
However, if a function load_from_buffer() is made freestanding, it can be overloaded for different types, such as int, char, double and with templates, an overload can be made to call objects derived from an interface.
Summary
Prefer to use member methods when they require access to data members of an object. Use static member methods when they access static data members or there is a need for the functionality without an instance of an object (think encapsulation). Freestanding functions also provide the capability of functionality to different objects based on function overloading.
There are no hard rules, just use what you think will be easiest to maintain, assist in correctness and robustness and speed up development.
Just to confuse people, here is an article by Scott Meyers:
How Non-Member functions increase encapsulation
Remember, in order for a free standing function to access data members of an object, the data members must be given public access or the function needs to be a friend of the object. The classic example is overloading the stream operators for a class.
The question is, what would be the best or maybe a better practice to use. Suppose I have a function, which belongs to some class and this function needs to use some static variable. There are two possible approaches - to declare this variable as class's member:
class SomeClass
{
public:
....
void someMethod();
private:
static int m_someVar;
};
SomeClass::someMethod()
{
// Do some things here
....
++m_someVar;
}
Or to declare it inside the function.
class SomeClass
{
public:
....
void someMethod();
};
SomeClass::someMethod()
{
static int var = 0;
++m_someVar;
// Do some things here
....
}
I can see some advantages for the second variant. It provides a better encapsulation and better isolates details of an implementation. So it would be easier to use this function in some other class probably. And if this variable should be modified only by a single function, then it can prevent some erroneous data corruption from other methods.
While it's quite obvious, that the first variant is the only one to use when you need to share a static variable among several methods (class functions), the question pertains the case when a static variable should be used only for a single function. Are there any advantages for the first variant in that case? I can think only about some multi threading related stuff...
It's simple - use a static member if, logically, it belongs to the class (sort of like instanceCounter) and use a static local if it logically belongs to a function (numberOfTimesThisMethodWasCalled).
The choice of static or not depends completely on the context. If a particular variable needs to be common among all the instances of a class, you make it static.
However, if a variable needs to be visible only in a function and needs to be common across every call of the function, just make it a local static variable.
The difference between static data members and static variable in a function is that first are initialized at start-up and the second first time the function is called (lazy initialization).
Lazy initialization can create problem when a function is used in a muti-threaded application, if it is not required by the design I prefer to use static members.
I have a class which I intend to use for performing calculations. I declare one static object of the class elsewhere which I use to obtain results. The class has one public function apart from the constructor.
public:
double getProbability(PlayerStats &p1, PlayerStats &p2, Score &score);
As you can see, I have three objects as input parameters. My class then has two private functions which are called from getProbability(). One requires p1 and p2, the other requires all three of the parameters
My question is this. Is it better to pass these objects as parameters to the function or is it better to create private member variables and use these.
So for example
double MyClass::getProbability(PlayerStats &p1, PlayerStats &p2, Score &score){
otherFunction(p1,p2);
anotherFunction(p1,p2,score);
....
}
or
double MyClass::getProbability(PlayerStats &p1, PlayerStats &p2, Score &score){
this->p1 = p1;
this->p2 = p2;
this->score = score;
otherFunction(); //use member variables in these functions
anotherFunction();
....
}
It's better to pass them as parameters, as they don't really represent class state and storing them as members will probably be more performance costly than simply continuing to pass around the references.
But it doesn't really look like your class has any state at all, which leads me to believe all of these methods should be free-functions in a suitable namespace rather than members of a class (perhaps you come from a Java background?).
I prefer passing the parameter to the private functions. As far as your class may be access by multiple concurrent threads, it is better to send each data to its related function.
You should pass the arguments directly to your other methods. Even if other functions used them it would be very confusing because nothing in the function signature indicates that those arguments would be kept around.
If you need some of these parameters in other functions and those parameters remain the same through several calls, you could refactor your class. It would take the ones which stay the same in the constructor and then function calls just pass in the ones which will change. It really depends on the needs of your application to determine whether this is a better approach.
I understand that one benefit of having static member functions is not having to initialize a class to use them. It seems to me that another advantage of them might be not having direct access to the class's not-static stuff.
For example a common practice is if you know that a function will have arguments that are not to be changed, to simply mark these constant. e.g.:
bool My_Class::do_stuff(const int not_to_be_changed_1,
std::vector<int> const * const not_to_be_changed_2)
{
//I can't change my int var, my vector pointer, or the ints inside it.
}
So is it valid to use static member functions to limit access. For example, lets say you have a function
void My_Class::print_error(const unsigned int error_no) {
switch (error_no) {
case 1:
std::cout << "Bad read on..." << std::endl;
break;
//...
default:
break;
}
}
Well here we're not going to be accessing any member variables of the class. So if I changed the function to:
static void My_Class::print_error(const unsigned int error_no) {
switch (error_no) {
case 1:
std::cout << "Bad read on..." << std::endl;
break;
//...
default:
break;
}
}
I'd now get an error, if I inadvertently tried to access one of my private var, etc. (unless I pass myself an instance of my class, which would be purposeful ^_^ !)
Is this a valid technique, similar to proactively making args that should not be changed constants?
What downsides might it have in terms of efficiency or use?
My chief reason for asking is that most of the "static" tutorials I read made no mention of using it in this way, so I was wondering if there was a good reason why not to, considering it seems like a useful tool.
Edit 1: A further logical justification of this use:
I have a function print_error,as outlined above. I could use a namespace:
namespace MY_SPACE {
static void print_error(...) {
...
}
class My_Class {
....
void a(void)
}
}
But this is a pain, because I now have to lengthen ALL of my var declarations, i.e.
MY_SPACE::My_Class class_1;
all to remove a function from my class, that essentially is a member of my class.
Of course there's multiple levels of access control for functions:
//can't change pointer to list directly
void My_Class::print_error(std::vector<int> const * error_code_list) {...}
//can't change pointer to list or list members directly
void My_Class::print_error(std::vector<int> const * const error_code_list) {...}
//can't change pointer to list or list members directly, access
//non-const member vars/functions
void My_Class::print_error(std::vector<int> const * const error_code_list) const {...}
//can't change pointer to list or list members directly, access
//non-static member vars/functions
static void My_Class::print_error(std::vector<int> const * const error_code_list) {...}
//can't change pointer to list or list members directly, access
//member vars/functions that are not BOTH static and const
static void My_Class::print_error(std::vector<int> const * const error_code_list) const {...}
Sure this is a bit atypical, but to lessening degrees so are using const functions and const variables. I've seen lots of examples where people could have used a const function, but didn't. Yet some people think its a good idea. I know a lot of beginning c++ programmers who wouldn't understand the implications of a const function or a static one. Likewise a lot would understand both.
So why are some people so adamantly against using this as an access control mechanism if the language/spec provides for it to be used as such, just as it does with const functions, etc.?
Any member function should have access to the other members of the object. Why are you trying to protect yourself from yourself?
Static members are generally used sparingly, factory methods for example. You'll be creating a situation that makes the next person to work with your code go "WTF???"
Don't do this. Using static as an access-control mechanism is a barbaric abomination.
One reason not to do this is because it's odd. Maintenance programmers will have a hard time understanding your code because it's so odd. Maintainable code is good code. Everybody gets const methods. Nobody gets static-as-const. The best documentation for your code is the code itself. Self-documenting code is a goal you should aspire to. Not so that you don't have to write comments, but so that they won't have to read them. Because you know they're not going to anyway.
Another reason not to do this is because you never know what the future will bring. Your print_error method above does not need to access the class' state -- now. But I can see how it one day might need to. Suppose your class is a wrapper around a UDP socket. Sometime in the middle of the session, the other end slams the door. You want to know why. The last messages you sent or received might hold a clue. Shouldn't you dump it? You need state for that.
A false reason to do this is because it provides member access control. Yes it does this, but there are already mechanisms for this. Suppose you're writing a function that you want to be sure doesn't change the state of the object. For instance, print_error shouldn't change any of the object's state. So make the method const:
class MyClass
{
public:
void print_error(const unsigned int error_no) const;
};
...
void MyClass::print_error(const unsigned int error_no) const
{
// do stuff
}
print_error is a const method, meaning effectively that the this pointer is const. You can't change any non-mutable members, and you can't call any non-const methods. Isn't this really what you want?
Static member functions should be used when they are relevant to the class but do not operate on an instance of the class.
Examples include a class of utility methods, all of which are static because you never need an actual instance of the utility class itself.
Another example is a class that uses static helper functions, and those functions are useful enough for other functions outside the class.
It is certainly fair to say that global scope functions, static member functions, and friend functions aren't quite orthogonal to one another. To a certain extent, this is largely because they are intended to have somewhat different semantic meaning to the programmer, even though they produce similar output.
In particular, the only difference between a static member method and a friend function is that the namespaces are different, the static member has a namespace of ::className::methodName and the friend function is just ::friendFunctionName. They both operate in the same way.
Well, actually there is one other difference, static methods can be accessed via pointer indirection, which can be useful in the case of polymorphic classes.
So the question is, does the function belong as "part" of the class? if so, use a static method. if not, put the method in the global scope, and make it a friend if it might need access to the private member variables (or don't if it doesn't)