c++ this pointer clarification

Thread Starter

TheFox

Joined Apr 29, 2009
66
So, I was wondering, would it be better to use this, as apposed to just using them as is?
e.g.,

Rich (BB code):
class clsExampleClass
{
     int AddTwoNumbers(int NumOne, int NumTwo)
     {
          return (NumOne + NumTwo);
     }

public:
     int TheSumOfTwoNumbers(int NumOne, int NumTwo)
     {
          return this->AddTwoNumbers(NumOne,NumTwo)
     }
};
OR, this

Rich (BB code):
class clsExampleClass
{
     int AddTwoNumbers(int NumOne, int NumTwo)
     {
          return (NumOne + NumTwo);
     }

public:
     int TheSumOfTwoNumbers(int NumOne, int NumTwo)
     {
          return AddTwoNumbers(NumOne,NumTwo)
     }
};
 

debjit625

Joined Apr 17, 2010
790
In C++ "this" keyword refers to a pointer. When you declare a function in C++,the compiler create exactly the function you ask for, but if you create a member function i.e.. a function that belongs to a class, the compiler will modify the function a bit .It will add a secrete parameter to your member function and that parameter is the pointer to the class itself and known as “this” and if you want to use that in your code you use it by using the "this" keyword.

Your both the codes are equivalent, you don't need to use the "this" keyword, when you are inside a class, compilers secretly use the "this" pointer. I have seen people using this keyword everywhere in their code, which actually does nothing to their code. Occasionally you will actually need "this" keyword.

In case of static member functions ,the compiler will not add the "this" pointer to the function.

Good Luck
 

Thread Starter

TheFox

Joined Apr 29, 2009
66
In C++ "this" keyword refers to a pointer. When you declare a function in C++,the compiler create exactly the function you ask for, but if you create a member function i.e.. a function that belongs to a class, the compiler will modify the function a bit .It will add a secrete parameter to your member function and that parameter is the pointer to the class itself and known as “this” and if you want to use that in your code you use it by using the "this" keyword.

Your both the codes are equivalent, you don't need to use the "this" keyword, when you are inside a class, compilers secretly use the "this" pointer. I have seen people using this keyword everywhere in their code, which actually does nothing to their code. Occasionally you will actually need "this" keyword.

In case of static member functions ,the compiler will not add the "this" pointer to the function.

Good Luck
Thanks. I should have guessed that the compiler would do that automatically. I don't know that much about static; I guess I know what I'll be reading about tomorrow.

When I first learned about "this" pointer, I tried to do something like

Rich (BB code):
class FailureExample
{
public:
     ~FailureExample()
     {
          delete this;
     }
};
Obviously, My compiler, and OS disapproved highly.
 
Last edited:

debjit625

Joined Apr 17, 2010
790
When we create some object in system's memory heap i.e.. to allocate memory dynamically at runtime we use the "new" operator and to release the memory we use "delete" operator. Another way to create an object is to create it in application's stack space, if you create something in stack you don’t need to release it, compiler will handle it for you. For example

Rich (BB code):
#include<iostream>
usingnamespace std;
class diode
{
};
int main()
{
diode d_stack;//allocate memory in stack
diode *d_heap = new diode;// allocate memory in heap.
delete d_heap;// release the memory.
return 0;
}
Now the "this" pointer is a pointer that refers to any particular object. In the above program we created two diode object one in application’s stack space "d_stack" and another in system heap "d_heap".Now the "delete" can only be used if the object is dynamically created using new operator ,so if you call delete in destructor of "d_stack" that is not correct as it was not allocated on heap rather it was created in stack.

For "d_heap" stuff it will compile and will not give any error.Like

Rich (BB code):
#include<iostream>
usingnamespace std;
class diode
{
public:
diode()
{
}
~diode()
{
cout<<"Destructor call\n";
delete this;
}
};
int main()
{
diode *d_heap = new diode;
system("pause");
return 0;
}
But you should not do it as first of all you will not able to create object of this class in stack space, and destructor are not used to destroy the object itself rather its used to destroy the data member of the class(object) as destructor is a member function and when you are inside it, the object(class) is still needed you can't destroy it.After you exit from destructor compilers do some job to clean things, if you destroy it before, you may have memory leak. Anyway C/C++ sets some rules for us programmers you follow them you will have less trouble ,of course you can bypass these rules that’s the power of the language and it's the reason that C/C++ is the industries most powerful and favored language.

A static member function is created once in static space of application's memory space like static data members, it is bounded to a particular class rather to the objects of that class, it's the reason that you can use a static function without an instance of the class just using the scope-resolution operator like this
Rich (BB code):
class Me {
public:
static void f(){};
};
int main() {
Me::f();
return 0;
}
In member functions the address of the current object is quietly passed as "this" pointer but in case of static member function "this" pointer is not pass and this is the reason that you can’t access data members inside static function. Only static data members can be access inside static function.

You could find a lot more over internet, it’s too big to explain these things in post.

Good Luck
 
Last edited:

Thread Starter

TheFox

Joined Apr 29, 2009
66
When we create some object in system's memory heap i.e.. to allocate memory dynamically at runtime we use the "new" operator and to release the memory we use "delete" operator. Another way to create an object is to create it in application's stack space, if you create something in stack you don’t need to release it, compiler will handle it for you. For example

Rich (BB code):
#include<iostream>
usingnamespace std;
class diode
{
};
int main()
{
diode d_stack;//allocate memory in stack
diode *d_heap = new diode;// allocate memory in heap.
delete d_heap;// release the memory.
return 0;
}
Now the "this" pointer is a pointer that refers to any particular object. In the above program we created two diode object one in application’s stack space "d_stack" and another in system heap "d_heap".Now the "delete" can only be used if the object is dynamically created using new operator ,so if you call delete in destructor of "d_stack" that is not correct as it was not allocated on heap rather it was created in stack.

For "d_heap" stuff it will compile and will not give any error.Like

Rich (BB code):
#include<iostream>
usingnamespace std;
class diode
{
public:
diode()
{
}
~diode()
{
cout<<"Destructor call\n";
delete this;
}
};
int main()
{
diode *d_heap = new diode;
system("pause");
return 0;
}
But you should not do it as first of all you will not able to create object of this class in stack space, and destructor are not used to destroy the object itself rather its used to destroy the data member of the class(object) as destructor is a member function and when you are inside it, the object(class) is still needed you can't destroy it.After you exit from destructor compilers do some job to clean things, if you destroy it before, you may have memory leak. Anyway C/C++ sets some rules for us programmers you follow them you will have less trouble ,of course you can bypass these rules that’s the power of the language and it's the reason that C/C++ is the industries most powerful and favored language.

A static member function is created once in static space of application's memory space like static data members, it is bounded to a particular class rather to the objects of that class, it's the reason that you can use a static function without an instance of the class just using the scope-resolution operator like this
Rich (BB code):
class Me {
public:
static void f(){};
};
int main() {
Me::f();
return 0;
}
In member functions the address of the current object is quietly passed as "this" pointer but in case of static member function "this" pointer is not pass and this is the reason that you can’t access data members inside static function. Only static data members can be access inside static function.

You could find a lot more over internet, it’s too big to explain these things in post.

Good Luck
Thanks, this had been very insightful, and lead me in the right way, as to what to look for in the internet.
EDIT: I was told that you should always use the constructor, even if you don't write one, just be cause it was "better". Is there anything other good reason than good style?
 
Last edited:

debjit625

Joined Apr 17, 2010
790
A constructor guarantees initialization .You can't initialize data members while defining them. For example
Rich (BB code):
class Me
{
 private:
      int i = 0;//Error you can't do this...
 public:
      int y;//proper way to declare.
      void myfunc()
     {
      y = 0;//initialize
     }
};
int main()
{
 Me me;
 cout<<me.y;//error 'y' is not initialized
 me.myfunc();//initializing 'y'
 cout<<me.y//Now its ok to use 'y'
 return 0;
}
In above code if you create an instance of "Me" class and try to use data member "y" you will get an error as its not initialized unless you call myfunc() which initialize "y".So to avoid this problem C++ use constructor, compiler automatically calls it at the time of object creation before any other operation, inside constructor we initialize our data members and which guarantees initialization.

Rich (BB code):
class Me
{
 private:
      int i = 0;//Error you can't do this...
 public:
      int y;//proper way to declare.
      Me()
     {
      y = 0;
     }
};
int main()
{
 Me me;//constructor is called at this point
 cout<<me.y;//ok
 return 0;
}
If your class have no constructor then compiler will create a default constructor as a safety net ,but that default constructor will not guarantee proper initialization of the object so you should always define one your self and initialize your data members inside it.

EDIT:
If you are asking about writing the default constructor ,then it's not needed as compiler will create it for you .For example both the code are equivalent

Rich (BB code):
class Me
{
 public:
 int i;
 Me()
 {
 }
};
And
Rich (BB code):
class Me
{
public:
 int i;
};
But you can see the data member "i" will be not initialized and you can run into trouble.

Thanks, this had been very insightful, and lead me in the right way, as to what to look for in the internet.
You are always welcome

Good Luck
 
Last edited:

Thread Starter

TheFox

Joined Apr 29, 2009
66
A constructor guarantees initialization .You can't initialize data members while defining them. For example
Rich (BB code):
class Me
{
 private:
      int i = 0;//Error you can't do this...
 public:
      int y;//proper way to declare.
      void myfunc()
     {
      y = 0;//initialize
     }
};
int main()
{
 Me me;
 cout<<me.y;//error 'y' is not initialized
 me.myfunc();//initializing 'y'
 cout<<me.y//Now its ok to use 'y'
 return 0;
}
In above code if you create an instance of "Me" class and try to use data member "y" you will get an error as its not initialized unless you call myfunc() which initialize "y".So to avoid this problem C++ use constructor, compiler automatically calls it at the time of object creation before any other operation, inside constructor we initialize our data members and which guarantees initialization.

Rich (BB code):
class Me
{
 private:
      int i = 0;//Error you can't do this...
 public:
      int y;//proper way to declare.
      Me()
     {
      y = 0;
     }
};
int main()
{
 Me me;//constructor is called at this point
 cout<<me.y;//ok
 return 0;
}
If your class have no constructor then compiler will create a default constructor as a safety net ,but that default constructor will not guarantee proper initialization of the object so you should always define one your self and initialize your data members inside it.

EDIT:
If you are asking about writing the default constructor ,then it's not needed as compiler will create it for you .For example both the code are equivalent

Rich (BB code):
class Me
{
 public:
 int i;
 Me()
 {
 }
};
And
Rich (BB code):
class Me
{
public:
 int i;
};
But you can see the data member "i" will be not initialized and you can run into trouble.


You are always welcome

Good Luck
I could be wrong, what what I learned was:

Rich (BB code):
class Greeting
{
public:
     int Integer;
};

int main()
{
     Greeting * Hello = new Greeting();
     delete Hello;
     return 0;
}
That you should have the () when you create the class to call the constructor. Otherwise, you don't use the constructor. But if you don't write a constructor, is still it better in anyway to do it that way?
 

debjit625

Joined Apr 17, 2010
790
That you should have the () when you create the class to call the constructor.
No their is nothing like that,when you create an object(an instance) of a class ,constructor will always be called no matters if you use parentheses "()" or not.
For example check this code...
Rich (BB code):
#include<iostream>
usingnamespace std;
class X
{
public:
int integer;
X()
{
cout<<"X constructor\n";
}
};
int main()
{
X * a = new X;
a->integer = 0;
delete a;
X * b = new X();
b->integer = 0;
delete b;
 
system("pause");
return 0;
}
You will see two times the "X constructor" as we created two objects "a" and "b","a" is without parentheses "()".

Parentheses are only used if you have some arguments to pass to the constructor like this
Rich (BB code):
#include<iostream>
usingnamespace std;
class X
{
public:
int integer;
X(int i)
{
integer = i;
cout<<"X constructor and value of integer is "<<integer<<endl;
}
};
int main()
{
X * a = new X(100);
delete a;
system("pause");
return 0;
}
Otherwise, you don't use the constructor
This will never happen as compiler will always call a constructor.If the compiler can't find one then it will create a default constructor.

Good Luck
 

Thread Starter

TheFox

Joined Apr 29, 2009
66
No their is nothing like that,when you create an object(an instance) of a class ,constructor will always be called no matters if you use parentheses "()" or not.
For example check this code...
Rich (BB code):
#include<iostream>
usingnamespace std;
class X
{
public:
int integer;
X()
{
cout<<"X constructor\n";
}
};
int main()
{
X * a = new X;
a->integer = 0;
delete a;
X * b = new X();
b->integer = 0;
delete b;
 
system("pause");
return 0;
}
You will see two times the "X constructor" as we created two objects "a" and "b","a" is without parentheses "()".

Parentheses are only used if you have some arguments to pass to the constructor like this
Rich (BB code):
#include<iostream>
usingnamespace std;
class X
{
public:
int integer;
X(int i)
{
integer = i;
cout<<"X constructor and value of integer is "<<integer<<endl;
}
};
int main()
{
X * a = new X(100);
delete a;
system("pause");
return 0;
}

This will never happen as compiler will always call a constructor.If the compiler can't find one then it will create a default constructor.

Good Luck
Thank you very much, for all your help. I was taught wrong. I was told that unless you put the (), it wouldn't use the constructor.
 
Top