What is the 'this' pointer? - c++

I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario:
void do_something_to_a_foo(Foo *foo_instance);
void Foo::DoSomething()
{
do_something_to_a_foo(this);
}
I grabbed that from someone else's post on here.
What does this point to? I'm confused. The function has no input, so what is this doing?

this refers to the current object.
The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a non-static member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x.

The short answer is that this is a special keyword that identifies "this" object - the one on which you are currently operating. The slightly longer, more complex answer is this:
When you have a class, it can have member functions of two types: static and non-static. The non-static member functions must operate on a particular instance of the class, and they need to know where that instance is. To help them, the language defines an implicit variable (i.e. one that is declared automatically for you when it is needed without you having to do anything) which is called this and which will automatically be made to point to the particular instance of the class on which the member function is operating.
Consider this simple example:
#include <iostream>
class A
{
public:
A()
{
std::cout << "A::A: constructed at " << this << std::endl;
}
void SayHello()
{
std::cout << "Hi! I am the instance of A at " << this << std::endl;
}
};
int main(int, char **)
{
A a1;
A a2;
a1.SayHello();
a2.SayHello();
return 0;
}
When you compile and run this, observe that the value of this is different between a1 and a2.

Just some random facts about this to supplement the other answers:
class Foo {
public:
Foo * foo () { return this; }
const Foo * cfoo () const { return this; /* return foo(); is an error */ }
};
Foo x; // can call either x.foo() or x.cfoo()
const Foo y; // can only call x.cfoo()
When the object is const, the type of this becomes a pointer to const.
class Bar {
int x;
int y;
public:
Bar () : x(1), y(2) {}
void bar (int x = 3) {
int y = 4;
std::cout << "x: " << x << std::endl;
std::cout << "this->x: " << this->x << std::endl;
std::cout << "y: " << y << std::endl;
std::cout << "this->y: " << this->y << std::endl;
}
};
The this pointer can be used to access a member that was overshadowed by a function parameter or a local variable.
template <unsigned V>
class Foo {
unsigned v;
public:
Foo () : v(V) { std::cout << "<" << v << ">" << " this: " << this << std::endl; }
};
class Bar : public Foo<1>, public Foo<2>, public Foo<3> {
public:
Bar () { std::cout << "Bar this: " << this << std::endl; }
};
Multiple inheritance will cause the different parents to have different this values. Only the first inherited parent will have the same this value as the derived object.

this is a pointer to self (the object who invoked this).
Suppose you have an object of class Car named car which have a non static method getColor(), the call to this inside getColor() returns the adress of car (the instance of the class).
Static member functions does not have a this pointer(since they are not related to an instance).

this means the object of Foo on which DoSomething() is invoked. I explain it with example
void do_something_to_a_foo(Foo *foo_instance){
foo_instance->printFoo();
}
and our class
class Foo{
string fooName;
public:
Foo(string fName);
void printFoo();
void DoSomething();
};
Foo::Foo(string fName){
fooName = fName;
}
void Foo::printFoo(){
cout<<"the fooName is: "<<fooName<<endl;
}
void Foo::DoSomething(){
do_something_to_a_foo(this);
}
now we instantiate objects like
Foo fooObject("first);
f.DoSomething();//it will prints out first
similarly whatever the string will be passed to Foo constructor will be printed on calling DoSomething().Because for example in DoSomething() of above example "this" means fooObject and in do_something_to_a_foo() fooObject is passed by reference.

Acc. to Object Oriented Programming with c++ by Balaguruswamy
this is a pointer that points to the object for which this function was called. For example, the function call A.max() will set the pointer this to the address of the object. The pointer this is acts as an implicit argument to all the member functions.
You will find a great example of this pointer here. It also helped me to understand the concept.
http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/

Nonstatic member functions such as Foo::DoSomething have an implicit parameter whose value is used for this. The standard specifies this in C++11 §5.2.2/4:
When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note ] If the function is a non-static member function, the this parameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4).
As a result, you need a Foo object to call DoSomething. That object simply becomes this.
The only difference (and it's trivial) between the this keyword and a normal, explicitly-declared const pointer parameter is that you cannot take the address of this.

It is a local pointer.It refers to the current object as local object

Related

Pointers to function member

Let me start stating I'm a self-made programming passionate, so forgive the unprofessional language, not speaking English very well I got support from translator. From what I've understood it seems that casting a pointer to an object and one of its functions member cannot be made to a dummy structure. In particular, the call to the member function cannot be made in this way:
#include <iostream>
struct _T{};
class Class1
{
public:
void print()
{ std::cout << "Class1::print ...." << std::endl; }
int sum(int value)
{ return m_dato+value; }
private:
int m_dato { 10 };
};
int main()
{
Class1 item;
void(_T::*func)();
int(_T::*fsum)(int);
Class1* p1=&item;
auto p2=reinterpret_cast<_T*>(p1);
func =reinterpret_cast<void(_T::*)()>(&Class1::print);
(p2->*func)();
fsum =reinterpret_cast<int(_T::*)(int)>(&Class1::sum);
auto dato=(p2->*fsum)(55);
std::cout << "Dato: " << dato << std::endl; // ok 65..
std::cout << "Fine procedura ...." << std::endl;
return 0;
}
Now besides guessing that the pointer to Class1 may not be contained in the _T pointer, I don't understand why this code works without problems on all conditions (in case the class is derived and the function is virtual, in the case of multiple inheritance, in the case that the function is present only in the base class, etc ...). At the end I'm not telling the compiler to call an address of a class (Class1), that the compiler knows well, and that this function is at some offset from the class pointer and that the signature of that function is similar to the one stored later after the cast.

Unexpected output value with class constructor and class member variable

I need to understand why x(x + 1) happened only after I get out of the constructor.
class A
{
protected:
int x;
public:
A(int x = 5) : x(x + 1)
{
cout << "In A::A x=" << x << endl;
}
operator int() const { return x; }
};
void main()
{
A a1(10);
cout << a1 << endl ;
}
I was thinking I will get:
In A:: An x=11
11
But somehow I've got:
In A:: An x=10
11
You have two variables named x.
Inside the body of the constructor the argument variable will shadow the member variable. Whenever you use x inside the body of the constructor, it will be the argument, not the member.
To use the member variable you need to explicitly fetch it from the object, like this->x.
General tip: Don't use the same name for symbols in nested scopes. Besides solving this problem, it will also make the code easier to read and understand.
Your parameter is hiding the member variable of the same name - your definition is equivalent to
class A
{
protected:
int y;
public:
A(int x = 5) : y(x + 1)
{
cout << "In A::A x=" << x << endl;
}
operator int() const { return y; }
};
When a parameter has the same name as a member, you need to explicitly refer to the member with this->.
(The initialiser list follows its own rules.)

Why am I getting an error when using &this?

I know that the this pointer is implicitly passed to member functions when they are called. When I try to get the address of this pointer (via &this), though, I get the compiler error "lvalue required". Why is this?
class st
{
int a,b;
public :
void print()
{
cout << &this; //gives lvalue required... why?
cout << this; //will print address of object.
}
}
this is not an lvalue but an prvalue. From [class.this]:
In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
Emphasis mine
& requires an lvalue so you cannot get the address of this.
Because this pointer is a rvalue. this pointer is a constant value, it is passed to the member function like a local variable, so it's value is stored in a memory location that would become invalid when returning from that function.
Presumably you're trying to print out the values in the object. cout doesn't know how to do this, and you have to teach it.
cout << *this;
might do this if cout knew how to do it, but you can teach it. Here's an example that is more natural c++. (You should also consider a constructor).
#include <iostream>
using namespace std;
class st
{
public:
int a,b;
};
std::ostream& operator<<(std::ostream& s, const st& val)
{
return s << "a:" << val.a << " b:" << val.b ;
}
int main() {
st foo;
foo.a = 1;
foo.b = 2;
cout << "foo is " << foo << endl;
}

Function pointer of a non-static member function of a class

I want to define a member function in class and use its pointer. I know that I can use static member function but the problem with it is that I can only access the static members of the class. Is there a way other than static member function to be able to get function pointer.
To be more specific: There is a library which I'm using which gets a function pointer as its input. I want to write a member function and assign its function pointer to that external library. Should I create an object of class or use this pointer to do this?
You can get the pointer of the method, but it has to be called with an object
typedef void (T::*MethodPtr) ();
MethodPtr method = &T::MethodA;
T *obj = new T();
obj->*method();
If you need to have non-object pointer and you want to use object then you have to store instance of object somewhere, but you are restricted to use only one object (singleton).
class T {
static T *instance;
public:
T::T() {
instance = this;
}
static void func() {
instance->doStuff();
}
void doStuff() {}
};
If library supports user data for function pointers, then you may have multiple instances
class T {
public:
static void func(void *instance) {
((T*)instance)->doStuff();
}
void doStuff() {}
};
If:
you want to get the function pointer of a nonstatic member from within the class
And use it within the class:
Then:
It can work, because when you get the member function address, there is a "this" pointer. The syntax was not obvious to me, and it may look somewhat ugly, but not TOO bad.
This may not be new to the true experts, but I have wanted to have this in my bag of tricks for a long time.
Here is a complete sample program:
#include <iostream>
class CTestFncPtr
{
public:
CTestFncPtr(int data) : mData(data)
{
// Switch = &CTestFncPtr::SwitchC; // Won't compile - wrong function prototype - this is type safe
if (data == 1)
Switch = &CTestFncPtr::SwitchA;
else
Switch = &CTestFncPtr::SwitchB;
}
void CallSwitch(char *charData)
{
(this->*Switch)(charData);
}
private:
void SwitchA(char * charData)
{
std::cout << "Called Switch A " << "Class Data is " << mData<<" Parameter is " << charData<< "\n";
Switch = &CTestFncPtr::SwitchB;
}
void SwitchB(char * charData)
{
std::cout << "Called Switch B " << "Class Data is " << mData<<" Parameter is " << charData<< "\n";
Switch = &CTestFncPtr::SwitchA;
}
void SwitchC()
{
}
void(CTestFncPtr::*Switch)(char * charData);
int mData;
};
int main(int argc, char * argv[])
{
CTestFncPtr item1(1);
item1.CallSwitch("Item1");
item1.CallSwitch("Switched call Item 1");
CTestFncPtr item2(0);
item2.CallSwitch("Item2");
item2.CallSwitch("Switched call Item 2");
return 0;
}

member variable

Can there be a member variable in a class which is not static but which needs to be defined
(as a static variable is defined for reserving memory)? If so, could I have an example? If not, then why are static members the only definable members?
BJARNE said if you want to use a member as an object ,you must define it.
But my program is showing error when i explicitly define a member variable:
class test{
int i;
int j;
//...
};
int test::i; // error: i is not static member.
In your example, declaring i and j in the class also defines them.
See this example:
#include <iostream>
class Foo
{
public:
int a; // Declares and defines a member variable
static int b; // Declare (only) a static member variable
};
int Foo::b; // Define the static member variable
You can now access a by declaring an object of type Foo, like this:
Foo my_foo;
my_foo.a = 10;
std::cout << "a = " << my_foo.a << '\n';
It's a little different for b: Because it is static it the same for all instance of Foo:
Foo my_first_foo;
Foo my_second_foo;
Foo::b = 10;
std::cout << "First b = " << my_first_foo.b << '\n';
std::cout << "Second b = " << my_second_foo.b << '\n';
std::cout << "Foo::b = " << Foo::b << '\n';
For the above all will print that b is 10.
in that case, you would use the initialization list of test's constructor to define the initial values for an instance like so:
class test {
int i;
int j;
//...
public:
test() : i(-12), j(4) {}
};
That definition reserves space for one integer, but there'll really be a separate integer for every instance of the class that you create. There could be a million of them, if your program creates that many instances of test.
Space for a non-static member is allocated at runtime each time an instance of the class is created. It's initialized by the class's constructor. For example, if you wanted the integer test::i to be initialized to the number 42 in each instance, you'd write the constructor like this:
test::test(): i(42) {
}
Then if you do
test foo;
test bar;
you get two objects, each of which contains an integer with the value 42. (The values can change after that, of course.)