C++ : friends of class and "this" pointer - c++

I have one little question for you :), I understand that every method "secretly" gets "this" pointer of some class that they are inside but why that wont happen to "friend" functions ?
Is it because they are NOT methods of class?
Can anyone explain whole machinery, i am very interested in how "this" really works!
thanks in advance! :)

friend functions and classes are just used for access control checked by the compiler.
friend functions are just standard functions, so there won't be any differences regarding calling conventions.
friend functions are not member of any class, so no this pointer is passed (as done with static member functions)
Non-static member function of a class will get a hidden this pointer (depending on the ABI this is often the first argument), static member functions don't get the this pointer because they don't act on instance data.
How exactly the this pointer is passed to a member function heavily depends on the used ABI, which depends on the architecture and operating system. Either it will be pushed on the stack, or it will be passed through a well known register.
Please consider reading "Where is the 'this' pointer stored in computer memory?".

"Friendship" and "Membership" are two different things. A function can be a member function or not, and independantly be a friend function or not.
You can declare a member function to be a friend function of another class, i.e.
class B{
friend void A::func(B);
//stuff
};
Here, the member function func from class A is declared as friend and can access B's private, and it will have a this pointer, that points to the object of class A on which func has been called.
The this pointer is an implicit parameter of non-static member functions, which is described in section 9.3.2 of the C++ Standard. How it is passed to the function depends on your compiler/architecture, i.e. it is implementation defined (so you might want to read your favorite compiler's documentation to learn about how it manages this pointers).

Related

static functions compiler optimization C++

I know that we should declare a function as static in a class if its a utility function or if we have to use in a singleton class to access private static member.
But apart from that does a static function provide any sort of compiler optimization too since it doesn't pass the "this" pointer? Why not just use the utility function through an already instantiated object of class? Or is it just a best practice to make utility functions as statics?
Thanks in advance.
The "non-passing-this" optimization can probably be done by the compiler once you turn the optimizations on. As I see it, a static function has rather idiomatic uses:
Implementing modules. There is a bit of overlap here with namespaces, and I would rather use namespaces.
Factories: you can make the constructor protected/private and then have several static functions (with different, explicit names) creating instances.
For function pointers: static functions do not require the slightly more complicated syntax of pointer to member function. That can be a plus when interacting with libraries written for C.
To keep yourself from using this and have the compiler to enforce it. It makes sense sometimes. For example, if you have a commutative operation that takes two instances, a static function that takes the two instances would emphasize (in my opinion) that the operation is commutative. Of course in many cases you would rather overload an operator.
In general a static function will ease namespace and "friend" clutter by prefixing an otherwise ordinary function with the name of a class, presumably because both are tightly related.
Static exists to associate a method with a class, rather than either:
Associating it with an instance of that class (like writing a normal, non-static member function).
Keeping it in the global namespace or whatever namespace you would otherwise be in (like declaring a function just in the file, not in a class).
Static says that 'conceptually this is something tied to/associated with this class, but it does not depend on any instance of that class'.
In more formal terms: a static member function is the same as a function declared outside of a class in all ways other than that it is part of that class's namespace and in that it has access rights to that class's private/protected data members.
Going back to your question:
There is no optimization gain here.
Utility function has nothing to do with it. It's whether or not it makes sense to scope the function in the class itself (rather than an instance of it).
It does not 'pass the this pointer' because there is no instance to speak of. You can call a static member function without ever invoking that class's constructor.

Hiding rule- do the arguments/return type have to be the same?

I have a few questions/a general question regarding hiding?
A base class has a function: f() a derived class now declares virtual f()
What happens if the derived function is const? Does this not hide?
What about if the return types are different?
The parameters are different?
One is static and the other not?
Just wondering which of these differences between the two functions cause hiding/do not cause hiding.
Hiding is about names, not signatures.
First thing first.
Hiding refers to the idea that if you override a base class function in a derived class then in that derived class the original base class method that you defined will be hidden. -- That said, if you need to access your definition of the function from the base class then you'd need to have this in your code to it is NOT hidden :
using baseClass::functionName();
Const - if you define a function twice once with const another without const they are different. Scott Mayers book effective c++ contains an excellent chapter explaining const and non const-ness, I suggest you read it for a thorough understanding.
Your can not over-ride a function by having different return types, it will probably give compile time error stating its ambiguous - test it out, to make sure.
You CAN however overload a function by having different argument list, that is how one would overload a function.
If you're confused between over-ride and over-load - then I suggest you also read up on that. In a nutshell, overload is when you have two functions in the same scope with different argument lists, where as override is when you redefine a base class virtual function in a derived class with the same argument list.

In C++, what is the difference between a method and a function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between a method and a function
I'm trying to get my terminology correct.
What is the difference between a method and a function, in regards to C++ specifically.
Is it that a method returns nothing and just preforms operations on its class; while a function has a return value?
As far as the C++ standard is concerned, there is no such thing as a "method". This terminology is used in other OO languages (e.g. Java) to refer to member functions of a class.
In common usage, you'll find that most people will use "method" and "function" more or less interchangeably, although some people will restrict use of "method" to member functions (as opposed to "free functions" which aren't members of a class).
Sorry, but this is one of my pet peeves. Method is just a generic OO-type term. Methods do not exist in C++. If you open the C++ standard, you won't find any mention of "methods". C++ has functions, of various flavors.
A method is a member function of a class, but in C++ they are more commonly called member functions than methods (some programmers coming from other languages like Java call them methods).
A function is usually meant to mean a free-function, which is not the member of a class.
So while a member function is a function, a function is not necessarily a member function.
Example:
void blah() { } // function
class A {
void blah() { } // member function (what would be a "method" in other languages)
};
blah(); // free functions (non-member functions) can be called like this
A ainst;
ainst.blah(); // member functions require an instance to invoke them on
The term "Method" is not used in c++, but rather member function.
If you are thinking about the difference between a procedure and a function then the difference in c++ is none. Pascal was pretty much the last language to make that distinction. (ADA was constructed later and used the term Procedure, thanks Brian Neal.)
Any function, member or not, declared as void, would be a Procedure in the old vocabulary.
A member function is a complex beast, a function is a simple function.
A member function
is a member of a class
can be private
can be protected
can be public
can be virtual
can be pure virtual
Even a method can have a return value.
A method is a function of a class. For example class "car" has a method "accelerate".

C++ proper usage, this pointer [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should I make explicit use of the this pointer?
I'm wondering about the proper usage of the "this" pointer.
I've seen someone create a class constructor with the argument passed variable passed in named 'data'.
However he had a private member variable named 'data' already thus he simply used:
this->data = data;
would have worked to simply use
data = data_in
(if the parameter was named data_in), and no need to invoke the "this" pointer and reference the member type.
Now I'm wondering, is this proper usage? Using this->member to reduce on naming complexity? I mean it works and I see that it accomplishes what was intended but I'm wondering if some of you more experienced C++ guys and girls can say a word or two if this is common practice?
Also, out of curiosity I've instrumented the code just to see what happens under the hood, and it seems the "this" pointer is invoked anyhow. I guess that's the way references to the class object are done anyways.
In most cases, specifically dereferencing the this pointer to access a non-static data-member of the class instance is unnecessary, but it can help with naming confusion, especially when the data-members of the class are defined in a separate header file from the code-module. However, it is necessary to use the this pointer if you are accessing a non-static data-member that is a member of a base-class that is a templated class. In other words, in a situation like:
template<typename T>
class base_class
{
protected:
int a;
};
template<typename T>
class derived_class : public base_class<T>
{
void function()
{
a = 5; //this won't work
this->a = 5; //this will work
}
};
you'll note that you must use the this pointer in order to properly resolve the inherited non-static data-member from the template base-class. This is due to the fact that base_class<T>::a is a dependent name, in this case dependent on the template parameter T, but when used without the this pointer, it is treated as a non-dependent name, and is therefore not looked up in the dependent base-class namespace. Thus without the specific dereference of the this pointer, you'll end up with a compiler error like "a was not declared in this scope", or something similar.
No accessing a class member as:
this->member = something;
is same as accessing the member by itself,
member = something;
The compiler sees both as same and their is no overhead involved. Even if you use the second format the compiler does the same as first format under the hood.
In short, trying to use either of the two formats with aim of improving performance is useless. Ofcourse, You might have to use the first format in some template cases( accessing non-static data members of a templated Base class) but that is not for performance.
Essentially identical, except as Jason pointed out.
The nice part is that if you use this-> most editors will code complete for you, saving you typing.
It is "correct", but it is also poor practice. Naming parameters the same as class members is a bad idea. Intentionally creating naming conflicts is a bad idea.
Scoping operators are designed for when naming conflicts are unavoidable, such as when overriding a base member, or when using two libraries with identifier names chosen independently. Don't consider them free license for doing stupid things.
Unless you're practicing for an obfuscated code contest. Then by all means introduce naming collisions.

c++: Difference between member and non member functions

What is the difference between member and non-member functions in C++?
There are several differences between a member function (which I will now call method) and a free function (which I will now call function).
First, let's just state that they are not so different. Object code can generally be compiled down to C (or assembly) which are procedural languages with no notion of methods. Both methods and functions are then called like subroutines.
Now that this is out of the way, let's look at the differences. They can be classified in two categories: conceptual and syntactic.
Syntactically
The syntax is the obvious part of any language, so it's the easiest to get out of the way.
First note: there are two different kinds of methods in C++ (and a number of other languages), the static methods and regular methods.
Both kinds of methods have full access to the class internals (protected and private sections) as well (of course) as access to the class public interface.
static methods are equivalent to friend functions (apart from some scoping differences).
Within a regular method, a special keyword (this in C++) allows access to the current object on which the method has been invoked (via the ., ->, .* or ->* operators).
A regular method may be const and/or volatile qualified, enabling it for (respectively) const and/or volatile qualified objects. For example, a non-const method cannot be called on a const object. This can be seen as qualifying this within the method, ie void Foo::bar() const has a this of type Foo const*.
A regular method may be marked as virtual. Virtuality enables runtime polymorphism by enabling overriding. I won't extend on this mechanism here, let's just note that functions cannot be virtual.
One often ignored point, is that methods (both static and regular) are scoped within the class. This is important for name lookup (of other methods or attributes/variables) as it means that the elements of the class have priority during lookup from a method on the elements declared outside of the class.
Since the qualification using this-> before attribute or methods is not mandatory, this comes handy in regular methods, though it may introduce subtle bugs. In static methods, it avoids qualifying by the class name the static attributes and methods one whishes to access.
Now that the main syntactic differences have been asserted, let's check the conceptual differences.
Conceptually
OOP is generally about tying together state and behavior (of this state). This is done by creating classes which group attributes (state) and behavior (methods) and (in theory) stating that only the methods can act on the state. Therefore, in OOP, the methods are responsible for implementing the behavior of the class.
The methods participate to the encapsulation of state (freeing clients from the implementation detail) and to the preservation of the class invariants (statements about the class state that hold true from its birth to its death, whatever you do with it).
C++
In C++, as we have seen previously, this is done by using different access levels (public, protected and private) and granting access to the non-public levels to a restricted portion of the code. Generally attributes will be private and thus only accessible to the class methods (and maybe some friends, for syntax quirks).
Note: I urge you not to use protected attributes, it's hard to track down their modifications and since the set of derived classes is unbounded... their implementation cannot be changed easily afterward.
However, beware that C++ discourages from bloating the interface with lots of methods.
The trouble is that because methods are responsible of maintaining invariants, the more there are and the more the responsability is spread, making it more difficult to track down bugs and ensure correctness. Also, since methods depends on the class internals, it makes change more costly.
Instead, in C++, it is generally advised to write a minimal set of methods and delegating the rest of the behavior to non-friend functions (as long as it doesn't increase the cost too much).
See Sutter's take on std::string in Monolith Unstrung.
The delegation to non-friend methods was emphasized by Sutter in its Interface Principle in which he states that functions that are delivered with the class (in the same file/same namespace) and use the class, are logically part of the class interface. He restates in Exceptional C++.
This answer is becoming rather long-winded, yet I suspect that I have overlooked differences that other would find critical... oh well.
A (non-static) member function has an implicit this argument, a non-member doesn't.
Syntactically, you pass that implicit argument on the left of the . or -> operator like.so() or like->so(), instead of as a function argument so( like ).
Likewise, when declaring a member function, you need to do so in the class of which it is a member:
class Class {
public:
void a_public_member_function();
};
Non-member functions are instead declared outside any class (C++ calls this "at namespace scope").
(Non-static) member functions can also be virtual, but non-member functions (and static member functions) cannot.
A non-static member function is invoked on objects of the class it belongs to. It has implicitly access to the this pointer representing the current object. Through this pointer, it may access other members easily and with full access privileges (i.e. access private members).
A non-member function has no implicit this. In the sample below, bar is a member function while freebar is not. Both do more or less the same, but note how bar gets an implicit object pointer via this (also only bar has privileged access to foo's members, freebar only has access to public members).
class foo {
public:
void bar() {
this->x = 0; // equivalent to x = 0;
}
int x;
};
void freebar(foo* thefoo) {
thefoo->x = 1;
}
// ...
foo f;
f.bar();
// f.x is now 0
freebar(&f);
// f.x is now 1
Semantically a member function is more than just a function with an implicit this parameter. It is meant to define the behaviour of an object (i.e. a car object would have drive(), stop() as member functions).
Note that there are also static member functions which have full privileges but don't get an implicit this nor are they invoked through an instance of the class (but rather through the full name of the class).
In the following code, f() is a member function of class Sample, and g() is a non-member function:
class Sample
{
void f();
};
void g();
Its very simple. Since f() is a member of the class Sample, so its called member function (of class Sample). And since g() is not member of any class, so its called non-member function.
A member function is invoked on an object and has access to the fields of the class.
Member functions can be polymorphic (via the virtual keyword) which is essential for OOP.
Member functions get called on instances and have a this pointer available; non-members don't.