Is there any difference between Namespace::* and traditional *? - c++

class C {
public:
int a;
int f();
};
int C::f() { return 0; }
int main() {
C c {1};
int(C::*pmf)() = &C::f;
// int(*pmf)() = &C::f; -> error can not convert int(*C::f)() to int(*f)().
}
Is there any difference between Namespace::* and * in ram or it is just checked by compiler? Is it syntactic sugar?

Of course: https://isocpp.org/wiki/faq/pointers-to-members
Non-static member functions have a hidden parameter that corresponds to the this pointer. The this pointer points to the instance data for the object.
The functions are physically not interchangable as members have an extra parameter - the object that you call it from. You cannot see it, but the compiler puts it in there. And when that object is missing, compiler obviously complains. This is not like C#, where every function is a member function, and some just happen to be static (fun fact: when passing a C# function to a third party, the object that it is attached to gets passed along with it to allow a valid call later. You may and may not be able to get away with emulating something similar here).

Related

Why are member functions in C++ accessed with dot operator after object name?

In Python any bound call to member funtion or method gets converted to unbound call, i.e: obj.method() is equivalent to method(obj). That's why the first parameter of every member function is itself.
Is there a similar concept in C++ that explains why member function are accessed with dot operator?
In C++, the dot ('.') is an operator, which allows you to access a member given and object. There is another operator, arrow ('->') which allows you to access a member of an object given a pointer to that object. Each of these works for both member variables and member functions.
Inside of each (non-static) member function, the code has access to a pointer to the object ('this'), which can be used as needed. Access to members of that object are also available there.
As to why dots are used? It's just a design choice that Bjarne Stroustrup (PBUH) made a few decades ago. It mimics C's access to a member of a struct.
There is no such concept that makes obj.method() and method(obj) equivalent in c++. There has been a proposal for Uniform Function Call Syntax that would make them call the same code, but as far as I can tell it does not seem that it will be adopted any time soon.
Early C++ was a superset of the C language (it was originally called "C with Classes"), so the use of the . comes from Kernigan and Ritchie's 1973 introduction of struct to the C language, meaning "member of instance".
In order for the compiler to determine which function you are calling, it needs to know which object you are acting on, and so the simple decision was made to re-use the existing member-access syntax (object.member) and pass the object address as an implicit argument.
Why a pointer? Because C didn't have references.
The original C++ compiler, CFront, translated "C with classes" and later C++ into C code before compiling to assembly. Backwards and binary compatibility with C was critical and in order for a member function to modify the object its being invoked against, it needs to be passed by pointer or reference. Since pointers were supported by C as well as C++ they chose pointers. So this is a pointer, not a reference.
Roughly the same thing happens in Python, the this just has to be explicit by the user:
# Python
class MyClassNameHere(object):
_a = -1
def __init__(self):
self._a = 0
def setA(self, a):
self._a = a
def getA(self):
return self._a
// C++
struct MyClassNameHere {
int a_;
MyClassNameHere() : a_(0) {}
void setA(int a) { a_ = a; }
int getA() const { return a_; }
};
Because C++ is strongly typed, having to specify the this parameter would be tediously verbose, and you'd have to be mindful of your const's:
struct MyClassNameHere {
int a_ = -1;
MyClassNameHere(MyClassNameHere* this) : a_(0) {}
void setA(MyClassNameHere* this, int a) { a_ = a; }
int setA(const MyClassNameHere* this) const { return a_; }
// ^^^^^
};

C++ non-static method folding

Referring to this question, stackoverflow.com/q/14188612, are there situations when the compiler folds the method instantiation of two objects?
Let's say we have the following class with a private "stateless" method add, that does not modify the class members:
class Element
{
public:
Class(int a, int b) : a_(a), b_(b)
{
c_ = add(a, b);
}
private:
int add(int a, int b)
{
return a + b;
}
private:
int a_;
int b_;
int c_;
}
int main(void)
{
Element a(1, 2);
Element b(3, 4);
}
Can we sometimes expect that add will actually be compiled as a static-like method? Or, to be more clear, the address of a.add to be equal to b.add (add stored only once).
This is merely a question related to understanding compiler optimizations.
The compiler will always generate one binary method/function for add,
independent of how many objects you have. Anything else isn´t just stupid, but impossible:
The compiler can´t possibly know/calculate how many objects will exist during runtime just from the code. While it is possible with your example, more complicated programs will instantiate variables (or not) based on input given at runtime (keyboard, files...).
Note that templates can lead to more than one generation, one for each template type used in the code (but for that, the code is enough to know everything, and it has nothing to do with the object count).
When you define a method inside the class definition it usually means that the method should be inlined into each caller. The compiler can choose not to, but quite often you might find that the method doesn't actually exist in your output program at all (not true in debug builds, of course).
For non-inline member functions, the standard says
There shall be at most one definition of a non-inline member function in a program
There is no entity in C++ b.add or a.add from which you can take the address. The address-of operator needs a qualified-id to a member function of the form C::m(...) to get the address of a function. In your case, the address of add is
auto ptr = &Element::add;
and is independent from any instance. This gives a member-function pointer, which can only be used to call the function together with an object, e.g. (a.*ptr)(0,1) or (b.*ptr)(2,3) if add were a public method.

C++ member function invocation

Ok so often times I have seen the following type of event handling used:
Connect(objectToUse, MyClass::MyMemberFunction);
for some sort of event handling where objectToUse is of the type MyClass. My question is how exactly this works. How would you convert this to something that would do objectToUse->MyMemberFunction()
Does the MyClass::MyMemberFunction give an offset from the beginning of the class that can then be used as a function pointer?
In addition to Mats' answer, I'll give you a short example of how you can use a non-static member function in this type of thing. If you're not familiar with pointers to member functions, you may want to check out the FAQ first.
Then, consider this (rather simplistic) example:
class MyClass
{
public:
int Mult(int x)
{
return (x * x);
}
int Add(int x)
{
return (x + x);
}
};
int Invoke(MyClass *obj, int (MyClass::*f)(int), int x)
{ // invokes a member function of MyClass that accepts an int and returns an int
// on the object 'obj' and returns.
return obj->*f(x);
}
int main(int, char **)
{
MyClass x;
int nine = Invoke(&x, MyClass::Mult, 3);
int six = Invoke(&x, MyClass::Add, 3);
std::cout << "nine = " << nine << std::endl;
std::cout << "six = " << six << std::endl;
return 0;
}
Typically, this uses a static member function (that takes a pointer as an argument), in which case the the objectToUse is passed in as a parameter, and the MyMemberFunction would use objectToUse to set up a pointer to a MyClass object and use that to refer to member variables and member functions.
In this case Connect will contain something like this:
void Connect(void *objectToUse, void (*f)(void *obj))
{
...
f(objectToUse);
...
}
[It is also quite possible that f and objectToUse are saved away somewhere to be used later, rather than actually inside Connnect, but the call would look the same in that case too - just from some other function called as a consequence of the event that this function is supposed to be called for].
It's also POSSIBLE to use a pointer to member function, but it's quite complex, and not at all easy to "get right" - both when it comes to syntax and "when and how you can use it correctly". See more here.
In this case, Connect would look somewhat like this:
void Connect(MyClass *objectToUse, void (Myclass::*f)())
{
...
objectToUse->*f();
...
}
It is highly likely that templates are used, as if the "MyClass" is known in the Connect class, it would be pretty pointless to have a function pointer. A virtual function would be a much better choice.
Given the right circumstances, you can also use virtual functions as member function pointers, but it requires the compiler/environment to "play along". Here's some more details on that subject [which I've got no personal experience at all of: Pointers to virtual member functions. How does it work?
Vlad also points out Functors, which is an object wrapping a function, allowing for an object with a specific behaviour to be passed in as a "function object". Typically this involves a predefined member function or an operatorXX which is called as part of the processing in the function that needs to call back into the code.
C++11 allows for "Lambda functions", which is functions declared on the fly in the code, that doesn't have a name. This is something I haven't used at all, so I can't really comment further on this - I've read about it, but not had a need to use it in my (hobby) programming - most of my working life is with C, rather than C++ although I have worked for 5 years with C++ too.
I might be wrong here, but as far as I understand,
In C++, functions with the same signature are equal.
C++ member functions with n parameters are actually normal functions with n+1 parameters. In other words, void MyClass::Method( int i ) is in effect void (some type)function( MyClass *ptr, int i).
So therefore, I think the way Connect would work behind the scenes is to cast the member method signature to a normal function signature. It would also need a pointer to the instance to actually make the connection work, which is why it would need objectToUse
In other words, it would essentially be using pointers to functions and casting them to a more generic type until it can be called with the parameters supplied and the additional parameter, which is the pointer to the instance of the object
If the method is static, then a pointer to an instance doesn't make sense and its a straight type conversion. I have not figured out the intricacies involved with non-static methods yet - a look at the internals of boost::bind is probably what you want to do to understand that :) Here is how it would work for a static function.
#include <iostream>
#include <string>
void sayhi( std::string const& str )
{
std::cout<<"function says hi "<<str<<"\n";
}
struct A
{
static void sayhi( std::string const& str )
{
std::cout<<"A says hi "<<str<<"\n";
}
};
int main()
{
typedef void (*funptr)(std::string const&);
funptr hello = sayhi;
hello("you"); //function says...
hello = (&A::sayhi); //This is how Connect would work with a static method
hello("you"); //A says...
return 0;
}
For event handling or callbacks, they usually take two parameters - a callback function and a userdata argument. The callback function's signature would have userdata as one of the parameters.
The code which invokes the event or callback would invoke the function directly with the userdata argument. Something like this for example:
eventCallbackFunction(userData);
In your event handling or callback function, you can choose to use the userdata to do anything you would like.
Since the function needs to be callable directly without an object, it can either be a global function or a static method of a class (which does not need an object pointer).
A static method has limitations that it can only access static member variables and call other static methods (since it does not have the this pointer). That is where userData can be used to get the object pointer.
With all this mind, take a look at the following example code snippet:
class MyClass
{
...
public:
static MyStaticMethod(void* userData)
{
// You can access only static members here
MyClass* myObj = (MyClass*)userdata;
myObj->MyMemberMethod();
}
void MyMemberMethod()
{
// Access any non-static members here as well
...
}
...
...
};
MyClass myObject;
Connect(myObject, MyClass::MyStaticMethod);
As you can see you can access even member variables and methods as part of the event handling if you could make a static method which would be invoked first which would chain the call to a member method using the object pointer (retrieved from userData).

What does operator()() define?

I'm sorry if this question gets reported but I can't seem to easily find a solution online. If I override operator()() what behavior does this define?
The operator() is the function call operator, i.e., you can use an object of the corresponding type as a function object. The second set of parenthesis contains the list of arguments (as usual) which is empty. For example:
struct foo {
int operator()() { return 17; };
};
int main() {
foo f;
return f(); // use object like a function
}
The above example just shows how the operator is declared and called. A realistic use would probably access member variables in the operator. Function object are used in many places in the standard C++ library as customization points. The advantage of using an object rather than a function pointer is that the function object can have data attached to it.

C++: when we should use "this->" PLUS parameters by reference

suppose we have a class
class Foo {
private:
int PARTS;
public:
Foo( Graph & );
int howBig();
}
int Foo::howBig() { return this->PARTS; }
int Foo::howBig() { return PARTS;       }
Foo::Foo( Graph &G ) {
<Do something with G.*>
}
Which one of howBig()-variants is correct?
The &-sign ensures that only the reference for Graph object
is passed to initialization function?
In C I would simply do something like some_function( Graph *G ),
but in C++ we have both & and *-type variables, never understood
the difference...
Thank you.
When you've local variable inside a member function, then you must have to use this as:
Foo::MemberFunction(int a)
{
int b = a; //b is initialized with the parameter (which is a local variable)
int c = this->a; //c is initialized with member data a
this->a = a; //update the member data with the parameter
}
But when you don't have such cases, then this is implicit; you need to explicity write it, which means in your code, both versions of howBig is correct.
However, in member initialization list, the rules are different. For example:
struct A
{
int a;
A(int a) : a(a) {}
};
In this code, a(a) means, the member data a is being initialized with the parameter a. You don't have to write this->a(a). Just a(a) is enough. Understand this visually:
A(int a) : a ( a ) {}
// ^ ^
// | this is the parameter
// this is the member data
You can use this-> to resolve the dependent name issue without explicitly having to spell out the name of the base. If the name of the base is big this could arguably improve readability.
This issue only occurs when writing templates and using this-> is only appropriate if they're member functions, e.g.:
template <typename T>
struct bar {
void func();
};
template <typename T>
struct foo : public bar {
void derived()
{
func(); // error
this->func(); // fine
bar<T>::func(); // also fine, but potentially a lot more verbose
}
};
Which one of howBig()-variants is correct?
both in your case, the compiler will produce the same code
The &-sign ensures that only the reference for Graph object is passed to initialization function? In C I would simply do something like some_function( Graph *G ), but in C++ we have both & and *-type variables, never understood the difference...
there is no difference as per the use of the variable inside the method(except syntax) - in the case of reference(&) imagine as if you've been passed an invisible pointer that you can use without dereferencing
it(the &) might be "easier" for clients to use
Both forms of Foo::howBig() are correct. I tend to use the second in general, but there are situations that involve templates where the first is required.
The main difference between references and pointers is the lack of "null references". You can use reference arguments when you don't want to copy the whole object but you want to force the caller to pass one.
Both are correct. Usually shorter code is easier to read, so only use this-> if you need it to disambiguate (see the other answers) or if you would otherwise have trouble understanding where the symbol comes from.
References can't be rebound and can't be (easily) bound to NULL, so:
Prefer references to pointers where you can use them. Since they cannot be null and they cannot be deleted, you have fewer things to worry about when using code that uses references.
Use const references instead of values to pass objects that are large (more than say 16 or 20 bytes) or have complex copy constructors to save copy overhead while treating it as if it was pass by value.
Try to avoid return arguments altogether, whether by pointer or reference. Return complex object or std::pair or boost::tuple or std::tuple (C++11 or TR1 only) instead. It's more readable.