If each member function is only contained once per class (to be shared by all instances) what exactly is the purpose of declaring a member function static? Is it like a function being declared const, in that it modifies a particular type of data (in this case, static data members)?
Normal member functions require a class instance to run. Static methods can be called directly without first creating an instance of the class.
Normal method:
MyClass myClass;
myClass.NormalMethod();
Static method:
MyClass::StaticMethod();
So normal methods are perfect for functions that work with the class data. If a method doesn't need to work with the class data, then it would be a candidate for possibly being made static.
Class methods, static or otherwise, can access private members of any of that class's objects, not just its own instance. Same goes for static methods, which don't have an instance unless you pass one to them.
You could also use a free function and declare it a friend, but a free function implies a higher level of abstraction that may operate on objects of different classes. A static class method says "I only make sense in light of my class"
One application of static methods is to create instances and return pointers. For example, there may be derived classes that the caller isn't supposed to know about - the "factory" function knows which derived class to use.
Of course when you need to create an object, you probably don't already have an object to use for that, and even if you do that other object isn't relevant.
Basically, sometimes some action is an aspect of the abstraction that a class provides, but that action isn't associated with a specific object - or at least not one that already exists. In that case, you should implement the action as a static function.
Similarly, some data is related to the abstraction provided by a class but not to a particular instance of that class. That data is probably best implemented as static member variables.
Related
I was just curious, does the creation of an object in C++ allocate space for a new copy of it's member functions? At the assembly or machine code level, where no classes exist, do all calls for a specific function from different objects of the same class actually refer to the same function pointer or are there multiple function blocks in memory and therefore different pointers for each and every member function of every object derived from the same class?
Usually languages implement functionalities as simply as possible.
Class methods are under the hood just simple functions containing object pointer as an argument, where object in fact is just data structure + functions that can operate on this data structure.
Normally compiler knows which function should operate on the object.
However if there is a case of polymorphism where function may be overriden.
Then compiler doesn't know what is the type of class, it may be Derived1 or Derived2.
Then compiler will add a VTable to this object that will contain function pointers to functions that could have been overridden.
Then for overridable methods the program will make a lookup in this table to see which function should be executed.
You can see how it can be implemented by seeing how polymorphism can be implemented in C:
How can I simulate OO-style polymorphism in C?
No, it does not. Functions are class-wide. When you allocate an object in C++ it will contain space for all its attributes plus a VTable with pointers to all its methods/functions, be it from its own class or inherited from parent classes.
When you call a method on that object, you essentially perform a look-up on that VTable and the appropriate method is called.
I have to create simple singleton object factory for some types of objects. The problem is that I can't find smart way to prevent user from creating object instances by constructors. I know that I can move constructors to private/protected section but how will the factory create new objects now when constructors are private/protected? Making factory a friend of every class isn't really smart as I need to predeclare factory in every header and write aditional "friend Factory;" in every class. How to do this correct?
In the class, add a static member as pointer to the same type of the class. This will be your singleton.
When initializing an instance, the constructor is ran.
If this is the first time, the static member is null (never initialized), run the constructor normally and set default values. In the end also set the static member to this. Now your singleton is initialized.
In subsequent constructor calls, the static pointer will not be null. Make a temporary pointer to the class type. Set this pointer to this, then set this to the static member and delete the pointer. This will delete the new instance and return the same static instance instead, everytime.
I realise that providing a method which returns a pointer to a private method breaks encapsulation, and exposes the field to anyone who uses the class. However, suppose the following:
You have a class which calls the method of another class (which expects a pointer to some private field), and the address of the private member is passed as a parameter to this method.
As far as I can see, as long as the private member's address is only exposed in a way controlled by the developer of the class, this doesn't break encapsulation (i.e. the developer knows exactly how it's going to be used). Of course, the method called could (assuming you didn't write it) expose the private member, but do we need to look that far ahead? I've seen this done countless times, so I guess it's not the result of bad design practises?
Is it bad practise to write method which take pointers to private members of other classes and modify them? Should each class only "look out for themselves"?
It would be a bad design because most classes have getters and setters to read and write to the object. So if that function needs to read and write then it should ask for object reference, not for pointer to any private memeber.
And in most of cases when function needs a reference for variable, it asks for reference to a constant value.
I realise that providing a method which returns a pointer to a private method breaks encapsulation, and exposes the field to anyone who uses the class.
This is not true to begin with.
A class that has a method that returns a pointer as part of its interface is absolutely fine, and the fact that it returns a member variable is an implementation detail that the outside world does not need to know.
Now, that being said, it is difficult to design a sane class interface that involves functions that return non-owning pointers, so it's something we tend to avoid.
Edit as far as the second part of the question goes:
Any class is supposed to sanely handle any possible permutation of usage of its public interface (including de-referencing any returned pointers). What or who uses the public interface is supposed to be entirely irrelevant, and you should assume that all users of the class will make use of the entire public API.
If you have parts of the class that you only want to make available to specific types or functions, then that's exactly what friend is for. But this has nothing to do with pointers to members, it applies to any and all parts of the class.
In C++ is it true that if you instantiate an object of a class, that for every
object all of methods of the class are copied for the new object?
I tried to point to a method of a class with two different objects, but I'd problems
with pointer to member.
Any idea?
In C++ is it true that if you instantiate an object of a class, that for every object all of methods of the class are copied for the new object?
No, member functions are not usually copied anywhere. A different implicit parameter this is instead passed to any non-static member function, for each object of that class-type.
No, that is absolutely not true.
Class instances (objects) contain data members. Function members look like they're "in" the class, but that's only for scoping and such: your function code doesn't "exist" inside the type, and it certainly doesn't exist inside the object†.
†I think it could, theoretically, in that the standard doesn't outright forbid it. But honestly, no. Just no.
The code for a class exists only once.
For getting a pointer to a member function (probably what you meant by method), take a look at std::function, and for attaching the function call to different objects, take a look at std::bind.
As I understand, each instance of a class has its own member variables in memory, so that it can store different values for different objects. However, it is not the same for member functions. Member functions are reused across objects of a class, so it only has one address with one block of memory to refer when needed by all objects.
Static function is made to access static members. However, static function also exists only one during the lifetime of its application. Aside from being the static accessor, at low level it is not different with normal class functions, isn't it? Or maybe I'm wrong, that each class has its own functions?
Non-static functions accept additional parameter, this, which is the pointer to the class instance with the instance-specific variables.
Static functions don't have this parameter (thus you can't use this in a static function and can only access static data members).
This differs from language to language, but in C or C++03 functions generally map on assembly functions; that is they exist once in memory (whether free functions, class functions or class static functions) and take arguments as parameters, including a this pointer for member functions that is implicit.
In C++11, lambda functions introduce a novelty: each instance of the so-called function will carry some state. From an implementation point of view, it therefore means that a "regular" function needs be created and it is associated to an anonymous bundle of data (if necessary). The function need not be duplicated each time the lambda is created, but the data does. One helpful figure is to remember that lambdas (in C++) replace function objects (or predicate objects): they are just syntactic sugar, the implementation is similar.
The only difference between static and member functions is that member functions always have the this pointer passed in automatically.
simply if it is referred, static functions creates a single set of memory for itself and are meant for static data-members which are generally not changeable. But non-static functions creates separate set of memories for each instances and are meant for both non-static and static data-members. If u require stable output go for static and if u require the alternate go for the non-static.