Hi I want to call an objects function in other function but i can't. Why ?
class class1
{
private:
int var;
public:
class1(int x);
void functionO();
};
class1::class1(int x)
{
var = x;
}
void class1::functionO()
{
cout<<"text";
}
void Callfunction()
{
object1->function0();
}
int main()
{
class1 *object1;
object1 = new class1(x);
Callfunction();
}
Compilator says that
'object1' : undeclared identifier
It seems logical but how can i call that objects function within a function ?
In this code:
void Callfunction()
{
object1->function0();
}
object1 is out-of-scope. That is, the compiler doesn't know about anything named object1 from within the scope of CallFunction().
Note that even if you had defined CallFunction after main(), this would still be true. All variables are local to the scope in which they are declared.
One option is to make object1 a global, and I'm sure that you will be advised to do this. But please don't. Global variables introduce state to your program, and along with it a host of other nasty problems that are hard to fix without tearing your program apart. Don't get in to the habit of using global variables to fix all manner of scoping issues. You will regret it.
Rather, why not just pass a class1 pointer to CallFunction()? Better yet, pass a reference.
void CallFunction(class1& obj1)
{
obj1.function0();
}
int main()
{
class1 *object1;
object1 = new class1(x);
Callfunction(*object1);
}
Your problem has nothing to do with the declaration order (before or after doesn't matter). Your object1 is a local variable of main. This means that it isn't visible outside of main, unless you explicitely pass it to the function needing it or store a pointer to it in a global variable (but please don't). To solve your problem you should therefore pass your object to Callfunction:
void Callfunction(class1& object1)
{
object1.function0();
}
int main()
{
class1 object1(x);//<-- This asumes that you have actually defined x
//somewhere, otherwise replace it with an actual value
Callfunction(object1);
}
Note that I took the liberty of clearing up the unneeded indirection (and the memory leak) by constructing the object on the stack instead of on the heap.
Pass your object as (reference) parameter to your function:
class class1
{
private:
int var;
public:
class1(int x);
void function0();
};
class1::class1(int x)
: var(x) // Note: Use member initializer lists
{}
void class1::function0()
{
std::cout << "text, var = " << var << std::endl;
}
void Callfunction(class1& object)
{
object.function0();
}
int main()
{
class1 object1(10);
class1 object2(42);
Callfunction(object1);
Callfunction(object2);
}
Expected output:
text, var = 10
text, var = 42
NOTE
The declaration order also matters, you might need to use a forward declaration when class1 is declared after the compiler sees Callfunction().
Related
Alright, I think the title is sufficiently descriptive (yet confusing, sorry).
I'm reading this library: Timer1.
In the header file there is a public member pointer to a function as follows:
class TimerOne
{
public:
void (*isrCallback)(); // C-style ptr to `void(void)` function
};
There exists an instantiated object of the TimerOne class, called "Timer1".
Timer1 calls the function as follows:
Timer1.isrCallback();
How is this correct? I am familiar with calling functions via function pointers by using the dereference operator.
Ex:
(*myFunc)();
So I would have expected the above call via the object to be something more like:
(*Timer1.isrCallback)();
So, what are the acceptable options for calling functions via function pointers, as both stand-alone function pointers and members of an object?
See also:
[very useful!] Typedef function pointer?
Summary of the answer:
These are all valid and fine ways to call a function pointer:
myFuncPtr();
(*myFuncPtr)();
(**myFuncPtr)();
(***myFuncPtr)();
// etc.
(**********************************f)(); // also valid
Things you can do with a function pointer.
1: The first is calling the function via explicit dereference:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
(*myfptr)(nValue); // call function myfunc(nValue) through myfptr.
2: The second way is via implicit dereference:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
myfptr(nValue); // call function myfunc(nValue) through myfptr.
As you can see, the implicit dereference method looks just like a normal function call -- which is what you’d expect, since function are simply implicitly convertible to function pointers!!
In your code:
void foo()
{
cout << "hi" << endl;
}
class TimerOne
{
public:
void(*isrCallback)();
};
int main()
{
TimerOne Timer1;
Timer1.isrCallback = &foo; //Assigning the address
//Timer1.isrCallback = foo; //We could use this statement as well, it simply proves function are simply implicitly convertible to function pointers. Just like arrays decay to pointer.
Timer1.isrCallback(); //Implicit dereference
(*Timer1.isrCallback)(); //Explicit dereference
return 0;
}
You don't have to dereference a function pointer to call it. According to the standard ([expr.call]/1),
The postfix expression shall have
function type or pointer to function type.
So (*myFunc)() is valid, and so is myFunc(). In fact, (**myFunc)() is valid too, and you can dereference as many times as you want (can you figure out why?)
You asked:
Timer1 calls the function as follows:
Timer1.isrCallback();
How is this correct?
The type of Timer1.isrCallback is void (*)(). It is a pointer to a function. That's why you can use that syntax.
It is similar to using:
void foo()
{
}
void test_foo()
{
void (*fptr)() = foo;
fptr();
}
You can also use:
void test_foo()
{
void (*fptr)() = foo;
(*fptr)();
}
but the first form is equally valid.
Update, in response to comment by OP
Given the posted definition of the class you would use:
(*Timer1.isrCallback)();
To use
(Timer1.*isrCallback)();
isrCallback has to be defined as a non-member variable of whose type is a pointer to a member variable of TimerOne.
void (TimerOne::*isrCallback)();
Example:
#include <iostream>
class TimerOne
{
public:
void foo()
{
std::cout << "In TimerOne::foo();\n";
}
};
int main()
{
TimerOne Timer1;
void (TimerOne::*isrCallback)() = &TimerOne::foo;
(Timer1.*isrCallback)();
}
Output:
In TimerOne::foo();
(Test this code)
If you want to define isrCallbak as a member variable of TimerOne, you'll need to use:
#include <iostream>
class TimerOne
{
public:
void (TimerOne::*isrCallback)();
void foo()
{
std::cout << "In TimerOne::foo();\n";
}
};
int main()
{
TimerOne Timer1;
Timer1.isrCallback = &TimerOne::foo;
// A little complicated syntax.
(Timer1.*(Timer1.isrCallback))();
}
Output:
In TimerOne::foo();
(Test this code)
When should I explicitly write this->member in a method of
a class?
Usually, you do not have to, this-> is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required.
Consider the following code:
template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
If you omit this->, some compilers do not know how to treat i. In order to tell it that i is indeed a member of A<T>, for any T, the this-> prefix is required.
Note: it is possible to still omit this-> prefix by using:
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.
#include <iostream>
using namespace std;
class A
{
public:
int a;
void f() {
a = 4;
int a = 5;
cout << a << endl;
cout << this->a << endl;
}
};
int main()
{
A a;
a.f();
}
prints:
5
4
There are several reasons why you might need to use this pointer explicitly.
When you want to pass a reference to your object to some function.
When there is a locally declared object with the same name as the member object.
When you're trying to access members of dependent base classes.
Some people prefer the notation to visually disambiguate member accesses in their code.
Although I usually don't particular like it, I've seen others use this-> simply to get help from intellisense!
There are few cases where using this must be used, and there are others where using the this pointer is one way to solve a problem.
1) Alternatives Available: To resolve ambiguity between local variables and class members, as illustrated by #ASk.
2) No Alternative: To return a pointer or reference to this from a member function. This is frequently done (and should be done) when overloading operator+, operator-, operator=, etc:
class Foo
{
Foo& operator=(const Foo& rhs)
{
return * this;
}
};
Doing this permits an idiom known as "method chaining", where you perform several operations on an object in one line of code. Such as:
Student st;
st.SetAge (21).SetGender (male).SetClass ("C++ 101");
Some consider this consise, others consider it an abomination. Count me in the latter group.
3) No Alternative: To resolve names in dependant types. This comes up when using templates, as in this example:
#include <iostream>
template <typename Val>
class ValHolder
{
private:
Val mVal;
public:
ValHolder (const Val& val)
:
mVal (val)
{
}
Val& GetVal() { return mVal; }
};
template <typename Val>
class ValProcessor
:
public ValHolder <Val>
{
public:
ValProcessor (const Val& val)
:
ValHolder <Val> (val)
{
}
Val ComputeValue()
{
// int ret = 2 * GetVal(); // ERROR: No member 'GetVal'
int ret = 4 * this->GetVal(); // OK -- this tells compiler to examine dependant type (ValHolder)
return ret;
}
};
int main()
{
ValProcessor <int> proc (42);
const int val = proc.ComputeValue();
std::cout << val << "\n";
}
4) Alternatives Available: As a part of coding style, to document which variables are member variables as opposed to local variables. I prefer a different naming scheme where member varibales can never have the same name as locals. Currently I'm using mName for members and name for locals.
Where a member variable would be hidden by
a local variable
If you just want
to make it explictly clear that you
are calling an instance method/variable
Some coding standards use approach (2) as they claim it makes the code easier to read.
Example:
Assume MyClass has a member variable called 'count'
void MyClass::DoSomeStuff(void)
{
int count = 0;
.....
count++;
this->count = count;
}
One other case is when invoking operators. E.g. instead of
bool Type::operator!=(const Type& rhs)
{
return !operator==(rhs);
}
you can say
bool Type::operator!=(const Type& rhs)
{
return !(*this == rhs);
}
Which might be more readable. Another example is the copy-and-swap:
Type& Type::operator=(const Type& rhs)
{
Type temp(rhs);
temp.swap(*this);
}
I don't know why it's not written swap(temp) but this seems to be common.
The other uses for this (as I thought when I read the summary and half the question... .), disregarding (bad) naming disambiguation in other answers, are if you want to cast the current object, bind it in a function object or use it with a pointer-to-member.
Casts
void Foo::bar() {
misc_nonconst_stuff();
const Foo* const_this = this;
const_this->bar(); // calls const version
dynamic_cast<Bar*>(this)->bar(); // calls specific virtual function in case of multi-inheritance
}
void Foo::bar() const {}
Binding
void Foo::baz() {
for_each(m_stuff.begin(), m_stuff.end(), bind(&Foo:framboozle, this, _1));
for_each(m_stuff.begin(), m_stuff.end(), [this](StuffUnit& s) { framboozle(s); });
}
void Foo::framboozle(StuffUnit& su) {}
std::vector<StuffUnit> m_stuff;
ptr-to-member
void Foo::boz() {
bez(&Foo::bar);
bez(&Foo::baz);
}
void Foo::bez(void (Foo::*func_ptr)()) {
for (int i=0; i<3; ++i) {
(this->*func_ptr)();
}
}
Hope it helps to show other uses of this than just this->member.
You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:
class A {
public:
void setMyVar(int);
void doStuff();
private:
int myVar;
}
void A::setMyVar(int myVar)
{
this->myVar = myVar; // <- Interesting point in the code
}
void A::doStuff()
{
int myVar = ::calculateSomething();
this->myVar = myVar; // <- Interesting point in the code
}
At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".
You need to use this to disambiguate between a parameters/local variables and member variables.
class Foo
{
protected:
int myX;
public:
Foo(int myX)
{
this->myX = myX;
}
};
The main (or I can say, the only) purpose of this pointer is that it points to the object used to invoke a member function.
Base on this purpose, we can have some cases that only using this pointer can solve the problem.
For example, we have to return the invoking object in a member function with argument is an same class object:
class human {
...
human & human::compare(human & h){
if (condition)
return h; // argument object
else
return *this; // invoking object
}
};
I found another interesting case of explicit usage of the "this" pointer in the Effective C++ book.
For example, say you have a const function like
unsigned String::length() const
You don't want to calculate String's length for each call, hence you want to cache it doing something like
unsigned String::length() const
{
if(!lengthInitialized)
{
length = strlen(data);
lengthInitialized = 1;
}
}
But this won't compile - you are changing the object in a const function.
The trick to solve this requires casting this to a non-const this:
String* const nonConstThis = (String* const) this;
Then, you'll be able to do in above
nonConstThis->lengthInitialized = 1;
I've applied solutions based on some search made, but the problem still there. Thank you so much for the help.
error: must use '.*' or '->*' to call pointer-to-member function ...
source code:
#include <stdio.h>
class A
{
public:
struct data;
typedef int (A::*func_t)(data *);
typedef struct data
{
int i;
func_t func;
}
data;
data d;
void process()
{
d.func(&d);
}
A()
{
d.i = 999;
d.func = &A::print;
}
int print(data *d)
{
printf("%d\n", d->i);
return 0;
}
};
int main()
{
A *a = new A;
a->process();
return 0;
}
d.func(&d);
is not enough. func is a member-function-pointer which is pointing to a non-static member of A. So it can be invoked on an object of A. So you need to write this:
(this->*(d.func))(&d);
That would work as long as you write this inside A.
If you want to execute func from outside, say in main(), then the syntax is this:
A a;
(a.*(a.d.func))(&a.d);
That is an ugly syntax.
Your process function attempts to call d.func but it is a pointer to member function. A pointer to member function must be called on some object. Presumably you want the instance of A to be this, in which case your process function should look like:
void process()
{
(this->*(d.func))(&d);
}
Note the use of the ->* operator to call a member function when you have a pointer to it.
Other answers have already said you need to say (this->*d.func)(&d) to call a pointer-to-member function (because you need to provide the object that it's a member of)
Another option is to make the function a static function, which doesn't need special syntax to call. To do that, change the typedef like so:
typedef int (*func_t)(data *);
Then make the print function static:
static int print(data *d)
{
...
}
Now you can just call d.func(&d)
Unfortunately what you are trying to do will not be possible, the reason being that print is not a static member function. This means it expects an implicit first argument that is the this pointer.
I suggest you try using the std::function and std::bind function, something like this:
class A
{
struct data
{
std::function<void(const data&)> func;
int i;
};
data d;
public:
A()
{
d.func = std::bind(&A::print, *this);
d.i = 999;
}
void process()
{
d.func(d);
}
void print(const data& my_data)
{
std::cout << my_data.i << '\n';
}
};
Of course, since the print function now have a proper this pointer, you no longer need to pass the data structure to it:
class A
{
struct data
{
std::function<void()> func;
int i;
};
data d;
public:
A()
{
d.func = std::bind(&A::print, *this);
d.i = 999;
}
void process()
{
d.func();
}
void print()
{
std::cout << d.i << '\n';
}
};
Calling pointer the members require the class it is a member of to be the this param.
Try:
A a;
a.*(d.func)(&d);
There are several duplicates of this but nobody explains why I can use a member variable to store the pointer (in FOO) but when I try it with a local variable (in the commented portion of BAR), it's illegal. Could anybody explain this?
#include <iostream>
using namespace std;
class FOO
{
public:
int (FOO::*fptr)(int a, int b);
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
fptr = &FOO::add_stuff;
cout<<(this->*fptr)(a,b)<<endl;
}
};
class BAR
{
public:
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
//int (BAR::*fptr)(int a, int b);
//fptr = &BAR::add_stuff;
//cout<<(*fptr)(a,b)<<endl;
}
};
int main()
{
FOO test;
test.call_adder(10,20);
return 0;
}
Apparently, you misunderstand the meaning of this->* in the call in FOO.
When you use this->* with the member fptr pointer, the this->* part has absolutely nothing to do with fptr being a member of FOO. When you call a member function using a pointer-to-member, you have to use the ->* operator (or .* operator) and you always have to specify the actual object you want to use with that pointer-to-member. This is what the this->* portion of the calling expression does. I.e. the call will always look as
(<pointer-to-object> ->* <pointer-to-member>) (<arguments>)
or as
(<object> .* <pointer-to-member>) (<arguments>)
The left-hand side of the call (<pointer-to-object> or <object> above) cannot be omitted.
In other words, it doesn't matter whether fptr is a member variable, local variable, global variable or any other kind of variable, the call through fptr will always look as
(this->*fptr)(a, b);
assuming that you want to invoke it with *this object. If, for another example, you want to invoke it for some other object pointed by pointer pfoo, the call will look as follows
FOO *pfoo;
...
(pfoo->*fptr)(a, b);
In your BAR class the call should look as (this->*fptr)(a,b) even though fptr is a local variable.
When you use a member function pointer, you need to specify the object on which it is acting.
I.e. you need to create a pointer to an instance of BAR (let's call it bar) and do:
(bar->*fptr)(a,b)
to call the function, or an instance of BAR and do:
(bar.*fptr)(a,b)
Put another way:
#include <iostream>
class BAR
{
int i;
public:
BAR(): i(0) {};
int AddOne() { return ++i; };
int GetI() { return i; };
}
int main()
{
BAR bar;
auto fPtr = &BAR::AddOne; // This line is C++0x only (because of auto)
std::cout << (bar.*fPtr)(); //This will print 1 to the console
std::cout << std::endl;
std::cout << bar.GetI(); //This will also print 1 to the console.
}
I don't think the usage of the variable itself is illegal. What's illegal is trying to call that method without a class instance.
That is, you should really call (someVar->*fptr)(a,b) where someVar is of type BAR*
BAR::call_adder() had a couple of problems. For one, you were mixing case. In C++, case is signifigant. BAR and bar are not the same. Second, you decalred and assigned the pointer fine, after fixing the case problems, but when you try to call through the pointer to a member function, you need to use operator ->* with a class object. Here's is call_adder() fixed
void call_adder(int a, int b)
{
int (BAR::*fptr)(int a, int b);
fptr = &BAR::add_stuff;
cout<<(this->*fptr)(a,b)<<endl;
}
When you invoke a member function of a class the compiler generates code to set 'this' while the function runs. When you call it from a function pointer that isn't done. There are ways to get around it but they aren't 'guaranteed' to work and are compiler dependent. You can do it as long as you're careful and know the possible problems you can run into.
When should I explicitly write this->member in a method of
a class?
Usually, you do not have to, this-> is implied.
Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required.
Consider the following code:
template<class T>
struct A {
T i;
};
template<class T>
struct B : A<T> {
T foo() {
return this->i; //standard accepted by all compilers
//return i; //clang and gcc will fail
//clang 13.1.6: use of undeclared identifier 'i'
//gcc 11.3.0: 'i' was not declared in this scope
//Microsoft C++ Compiler 2019 will accept it
}
};
int main() {
B<int> b;
b.foo();
}
If you omit this->, some compilers do not know how to treat i. In order to tell it that i is indeed a member of A<T>, for any T, the this-> prefix is required.
Note: it is possible to still omit this-> prefix by using:
template<class T>
struct B : A<T> {
int foo() {
return A<T>::i; // explicitly refer to a variable in the base class
//where 'i' is now known to exist
}
};
If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.
#include <iostream>
using namespace std;
class A
{
public:
int a;
void f() {
a = 4;
int a = 5;
cout << a << endl;
cout << this->a << endl;
}
};
int main()
{
A a;
a.f();
}
prints:
5
4
There are several reasons why you might need to use this pointer explicitly.
When you want to pass a reference to your object to some function.
When there is a locally declared object with the same name as the member object.
When you're trying to access members of dependent base classes.
Some people prefer the notation to visually disambiguate member accesses in their code.
Although I usually don't particular like it, I've seen others use this-> simply to get help from intellisense!
There are few cases where using this must be used, and there are others where using the this pointer is one way to solve a problem.
1) Alternatives Available: To resolve ambiguity between local variables and class members, as illustrated by #ASk.
2) No Alternative: To return a pointer or reference to this from a member function. This is frequently done (and should be done) when overloading operator+, operator-, operator=, etc:
class Foo
{
Foo& operator=(const Foo& rhs)
{
return * this;
}
};
Doing this permits an idiom known as "method chaining", where you perform several operations on an object in one line of code. Such as:
Student st;
st.SetAge (21).SetGender (male).SetClass ("C++ 101");
Some consider this consise, others consider it an abomination. Count me in the latter group.
3) No Alternative: To resolve names in dependant types. This comes up when using templates, as in this example:
#include <iostream>
template <typename Val>
class ValHolder
{
private:
Val mVal;
public:
ValHolder (const Val& val)
:
mVal (val)
{
}
Val& GetVal() { return mVal; }
};
template <typename Val>
class ValProcessor
:
public ValHolder <Val>
{
public:
ValProcessor (const Val& val)
:
ValHolder <Val> (val)
{
}
Val ComputeValue()
{
// int ret = 2 * GetVal(); // ERROR: No member 'GetVal'
int ret = 4 * this->GetVal(); // OK -- this tells compiler to examine dependant type (ValHolder)
return ret;
}
};
int main()
{
ValProcessor <int> proc (42);
const int val = proc.ComputeValue();
std::cout << val << "\n";
}
4) Alternatives Available: As a part of coding style, to document which variables are member variables as opposed to local variables. I prefer a different naming scheme where member varibales can never have the same name as locals. Currently I'm using mName for members and name for locals.
Where a member variable would be hidden by
a local variable
If you just want
to make it explictly clear that you
are calling an instance method/variable
Some coding standards use approach (2) as they claim it makes the code easier to read.
Example:
Assume MyClass has a member variable called 'count'
void MyClass::DoSomeStuff(void)
{
int count = 0;
.....
count++;
this->count = count;
}
One other case is when invoking operators. E.g. instead of
bool Type::operator!=(const Type& rhs)
{
return !operator==(rhs);
}
you can say
bool Type::operator!=(const Type& rhs)
{
return !(*this == rhs);
}
Which might be more readable. Another example is the copy-and-swap:
Type& Type::operator=(const Type& rhs)
{
Type temp(rhs);
temp.swap(*this);
}
I don't know why it's not written swap(temp) but this seems to be common.
The other uses for this (as I thought when I read the summary and half the question... .), disregarding (bad) naming disambiguation in other answers, are if you want to cast the current object, bind it in a function object or use it with a pointer-to-member.
Casts
void Foo::bar() {
misc_nonconst_stuff();
const Foo* const_this = this;
const_this->bar(); // calls const version
dynamic_cast<Bar*>(this)->bar(); // calls specific virtual function in case of multi-inheritance
}
void Foo::bar() const {}
Binding
void Foo::baz() {
for_each(m_stuff.begin(), m_stuff.end(), bind(&Foo:framboozle, this, _1));
for_each(m_stuff.begin(), m_stuff.end(), [this](StuffUnit& s) { framboozle(s); });
}
void Foo::framboozle(StuffUnit& su) {}
std::vector<StuffUnit> m_stuff;
ptr-to-member
void Foo::boz() {
bez(&Foo::bar);
bez(&Foo::baz);
}
void Foo::bez(void (Foo::*func_ptr)()) {
for (int i=0; i<3; ++i) {
(this->*func_ptr)();
}
}
Hope it helps to show other uses of this than just this->member.
You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:
class A {
public:
void setMyVar(int);
void doStuff();
private:
int myVar;
}
void A::setMyVar(int myVar)
{
this->myVar = myVar; // <- Interesting point in the code
}
void A::doStuff()
{
int myVar = ::calculateSomething();
this->myVar = myVar; // <- Interesting point in the code
}
At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".
You need to use this to disambiguate between a parameters/local variables and member variables.
class Foo
{
protected:
int myX;
public:
Foo(int myX)
{
this->myX = myX;
}
};
The main (or I can say, the only) purpose of this pointer is that it points to the object used to invoke a member function.
Base on this purpose, we can have some cases that only using this pointer can solve the problem.
For example, we have to return the invoking object in a member function with argument is an same class object:
class human {
...
human & human::compare(human & h){
if (condition)
return h; // argument object
else
return *this; // invoking object
}
};
I found another interesting case of explicit usage of the "this" pointer in the Effective C++ book.
For example, say you have a const function like
unsigned String::length() const
You don't want to calculate String's length for each call, hence you want to cache it doing something like
unsigned String::length() const
{
if(!lengthInitialized)
{
length = strlen(data);
lengthInitialized = 1;
}
}
But this won't compile - you are changing the object in a const function.
The trick to solve this requires casting this to a non-const this:
String* const nonConstThis = (String* const) this;
Then, you'll be able to do in above
nonConstThis->lengthInitialized = 1;