c++ classes, const function that calls non constant function - c++

in C++ classes, if I have a constant function (In my understanding constant functions are classes that cannot change anyting in the class, hope this is true)
for example a function like this
int output(int value) const
Am I allowed to call a function within this function remove that actually changes anything in the class?
For example lets say I have a variable called number in private.
my output function adds one to the variable number, but not directly, it calls
a non constant function called addOne which adds one to the variable number.
I notice that I am getting an error when a output function is calling addOne(I know that output function is const but it modifies a value, but it modifies it indirectly). I wonder why I am getting an error, what error compiler actually detects here?
Thank You, and sorry if my question is hard to understand.
Thank you all for answering.

The answer is simple - no, you cannot. Every class method is a function that implicitly passes this as a parameter. When you declare a method as const, that means that it will actually pass const this to this function. It is both correct logically and syntactically not to call not const methods from const methods.

const instances can only call const functions. Say:
class YourClass {
...
int output(int value) const;
int regularMethod(); // Non-const
...
};
is your class with a const function. And the variables:
const YourClass obj1;
YourClass obj2;
Here obj1 can call output method while it cant call regularMethod. obj2 can call both.

Every const function() is getting a const this pointer as a default parameter, so you cannot change a member variable of a class even if you try to call a non_cost function from a const function and try to modify a member variable.
So if you try to call a non const function from a const function, you will get compile error.

The answer is NO. The long answer is perhaps YES, provided you use an abomination like this, via const_cast-ing this in the const calling function (but you have to make sure you invoke your function on non-const objects, otherwise it leads to undefined behaviour):
#include <iostream>
struct Foo
{
int x = 0;
void f()
{
++x;
}
void modify_x() const
{
const_cast<Foo*>(this)->f(); // call non-const member function
}
};
int main()
{
Foo foo;
std::cout << foo.x << std::endl;
foo.modify_x();
std::cout << foo.x << std::endl;
}

Related

C++ pointer to a function

In my code I would like to call different functions by the same name. So I used pointers, and I did work with static functions, now I would like to do the same with non-static functions and it doesn't work at all.
class Amrorder
: {
public:
....
void (*fkt)(real&, const real);
void fktAcPulse(real &rhoRef, const real y);
void fktAcPulseSol(real &rhoRef, const real y);
...
}
void Amrorder::initData(a)
{
...
switch(method){
case 2://
Amrorder::fkt=&Amrorder::fktAcPulse;
break;
case 222://
Amrorder::fkt=&Amrorder::fktAcPulse1d;
break;
}
...
for(int i=0; i<ng; ++i){
Amrorder::fkt(rhoRef, yRef);
...
}
...
}
The code is quiet big so I hope the part above is enough to understand what I want to do.
Thanks for your time!
It doesn't work because your fkt has type:
void (*)(real&, const real);
and you're trying to assign it to, e.g., &Amrorder::fktAcPulse, which has type:
void (Amrorder::*)(real&, const real);
Notice the difference. The latter is a pointer-to-member function, not just a pointer to function. These have different semantics. A pointer to function can just be called (e.g. fkt(a, b)), but a pointer to member function needs to be called on an object (e.g. (obj.*pm)(a, b)).
For simplicity, since you probably just want "something that I can call with a real& and a const real", you may want to consider the type-erased function object: std::function:
std::function<void(real&, const real)> fkt;
This can be initialized with any callable that matches the arguments, so you can assign it to a free function:
void foo(real&, const real) { ... }
fkt = foo;
A static member function:
struct S { static void bar(real&, const real) { ... } };
fkt = &S::bar;
Or a member function, as long as its bound:
fkt = std::bind(&Amrorder::fktAcPulse, this);
fkt = [this](real& a, const real b){ return this->fktAcPulse(a, b); };
The key is that you need an instance of Amrorder to call fktAcPulse, and using std::function lets you use either std::bind or a lambda to store that instance in with the functor itself.
The type of fkt declares a function pointer to a free-standing function or a static member function. But you want to assign a non-static member function pointer to it. So fkt needs to be of the type of a non-static member function pointer of class Amrorder. That type is spelled
void (Amrorder::*fkt)(real&, const real);
// ^^^^^^^^^^
When invoking a function pointer to a non-static member function, you need to specify on which object you want the member to be called (which normally defaults to this when calling a member function directly with its name).
The syntax for this is quite strange. It requires another pair of parentheses and depends on wether you call it on a pointer or an object itself:
(object.*functionPointer)(arguments);
(pointer->*functionPointer)(arguments);
So if you just want to call the function on the this pointer, you need to write
(this->*fkt)(rhoRef, yRef);
(Note that you don't need to specify the class in your code everywhere. Amrorder:: can be removed in front of every function name inside the definition of a member function of the same class.)
When you call a non-static method of a class, the compiler needs to know which instance of the class you want to execute against. So there is a hidden parameter in the call, which is a pointer to the instance.
So you need to write something like this:
Amrorder::fkt=bind( &Amrorder::fktAcPulse, this );

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.

Cast const member function to non-const

Is casting the constness of member function pointers defined in C++? Is the following valid code?
struct T {
void foo(int i) const { std::cout << i << std::endl;};
};
void (T::*f1)(int) const = &T::foo;
void (T::*f2)(int) = reinterpret_cast<void (T::*)(int)>(f1);
T t;
(t.*f2)(1);
Update:
The reason why I need this is that I'm writing a function that accepts both an object and a member function pointer to that object. I need a version for const objects (accepting only const functions) and a normal one. Since I don't want duplicate code, my idea was to put the actual code in the non-const version and call it from the const one, casting away any consts.
Compiler eats it.
But the backward cast is more useful.
And again but - it is better to don't use it, const_cast is usually just a quick and dirty solution, which you apply only when there are not any other solution.
Answer to update
If I understand you correctly you are going to use one object and two function. First function accepts const object and const member-function, second - non-const object and non-const member-function.
According to given information you can change second function to accept non-const object and const member-function. And give them one non-const object and its const member-function.
Yes, it is defined, but you maybe don't want it if the function is really const, because some compiler optimizations (namely return value caching) depend on the function being const.
You can do it, but it has no meaning, wherever you can call f2, you can also call f1 too. You should cast in the other way. But if something, you should cast the object, not the function.
void (T::*f1)(int) const = &T::foo;
void (T::*f2)(int) = reinterpret_cast<void (T::*)(int)>(f1);
T t;
(t.*f2)(1); // compiles
(t.*f1)(1); // this compiles too!!
but if you have
const T t;
(t.*f2)(1); // error t is const
(t.*f1)(1); // still compiles
The only was to resolve the ambiguity is to perform a static_cast, this is basically a language feature
#include <boost/typeof/typeof.hpp>
struct Test
{
const int& foo();
const int& foo() const;
};
int main()
{
typedef const int&(Test::*non_const_ptr)();
typedef const int&(Test::*const_ptr)()const;
BOOST_TYPEOF(static_cast<non_const_ptr>(&Test::foo)) ss;
}
I don't see a reason for doing this: even if you could, you'd make it more restrictive.
Let's say you have a class Foo:
class Foo {
void f() const;
void g();
}
And some snippet of code:
Foo a;
const Foo b;
Then you can call both a.f() and a.g(), but not b.g() because b is const. As you can see, placing const after a member function makes it less restrictive, not more.
And, by reinterpret_casting this pointer, you'll get the pointer with exact same value(due to the nature of reinterpret_cast), and if you try to call it, you'll get into the same T::foo()

Using 'const' in class's functions [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 5 years ago.
I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .
It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way.
class Class2
{ void Method1() const;
int MemberVariable1;}
So, what is the real definition and use of const ?
A const method can be called on a const object:
class CL2
{
public:
void const_method() const;
void method();
private:
int x;
};
const CL2 co;
CL2 o;
co.const_method(); // legal
co.method(); // illegal, can't call regular method on const object
o.const_method(); // legal, can call const method on a regulard object
o.method(); // legal
Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:
void CL2::const_method() const
{
x = 3; // illegal, can't modify a member in a const object
}
There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.
Others have answered the technical side of your question about const member functions, but there is a bigger picture here -- and that is the idea of const correctness.
Long story short, const correctness is about clarifying and enforcing the semantics of your code. Take a simple example. Look at this function declaration:
bool DoTheThing(char* message);
Suppose someone else wrote this function and you need to call it. Do you know what DoTheThing() does to your char buffer? Maybe it just logs the message to a file, or maybe it changes the string. You can't tell what the semantics of the call are by just looking at the function declaration. If the function doesn't modify the string, then the declaration is const incorrect.
There's practical value to making your functions const correct, too. Namely, depending on the context of the call, you might not be able to call const-incorrect functions without some trickery. For example, assume that you know that DoTheThing() doesn't modify the contents of the string passed to it, and you have this code:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(msg.c_str());
}
The above code won't compile because msg.c_str() returns a const char*. In order to get this code to compile, you would have to do something like this:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(msg.begin());
}
...or even worse:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(const_cast<char*>(msg.c_str()));
}
neither of which, arguably, are 'better' than the original code. But because DoTheThing() was written in a const-incorrect way, you have to bend your code around it.
The meaning is that you guarantee to clients calling a const function member that the state of the object will not change. So when you say a member function is const it means that you do not change any of the objects member variables during the function call.
const, when attached to a non-static class method, tells the compiler that your function doesn't modify the internal state of the object.
This is useful in two ways:
If you do write code that changes internal state in your const method, the compiler catches the error, moving a programming error from run-time to compile-time.
If client code calls a non-const method on a constant pointer, the compiler catches the error, ensuring the "chain of not changing things" is maintained.
Typically you want to declare all non-mutating non-static class methods as const. This allows calling code to use the const qualifier on pointers, and it helps catch mistakes.
Typical C++: you can declare a class member variable "mutable" and then change it even from a const method.
The const keyword used after a method indicate that this method doesn't modify the object on which it's called. This way, this method can be called on a const version of the object.
If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way?
Well, no. Sometimes you do want instance methods to modify members. For example, any set method will obviously need to set variables, so it's not the case that you should put const everywhere. But if your object's state is totally immutable, first consider whether it might not be better to have no instances at all (i.e., a static class), and if that's not the case, then make everything const.
It's quite unusual not to want to have any member variables changed, but if that's what your class requires, then you should make all your member functions const.
However, you probably do want to change at least some members:
class A {
private:
int val;
public:
A() : val(0) {}
void Inc() { val++; }
int GetVal() const { return val; };
};
Now if I create two instances of A:
A a1;
const A a2;
I can say:
a1.GetVal();
a2.GetVal();
but I can only say:
a1.Inc();
trying to change the value of a constant object:
a2.Inc();
gives a compilation error.