Answers for "use of this pointer in c++"

C++
1

What is This pointer? Explain with an Example.

Every object in C++ has access to its own address through an important pointer called this pointer.
The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.

Example:
#include <iostream>
using namespace std;
class Demo {
private:
  int num;
  char ch;
public:
  void setMyValues(int num, char ch){
    this->num =num;
    this->ch=ch;
  }
  void displayMyValues(){
    cout<<num<<endl;
    cout<<ch;
  }
};
int main(){
  Demo obj;
  obj.setMyValues(100, 'A');
  obj.displayMyValues();
  return 0;
}
Posted by: Guest on November-30-2020
3

Function pointer C++

void one() { cout << "Onen"; }
void two() { cout << "Twon"; }


int main()
{
	void (*fptr)(); //Declare a function pointer to voids with no params

	fptr = &one; //fptr -> one
	*fptr(); //=> one()

	fptr = &two; //fptr -> two
	*fptr(); //=> two()

	return 0;
}
Posted by: Guest on July-30-2020
2

pointer c++

int myvar = 6;
int pointer = &myvar; // adress of myvar
int value = *pointer; // the value the pointer points to: 6
Posted by: Guest on September-12-2021
2

pointer in c++

// Variable is used to store value
int a = 5;
cout << a; //output is 5

// Pointer is used to store address of variable
int a = 5;
int *ab;
ab = &a; //& is used get address of the variable
cout << ab; // Output is address of variable
Posted by: Guest on May-27-2021
1

pointers c++

baz = *foo;
Posted by: Guest on February-18-2021
2

this in c++

#include <iostream>
class Entity
{
public:
	int x, y;
	Entity(int x, int y)
	{
		Entity*const e = this;// is a ptr to the the new instance of class 
		//inside non const method this == Entity*const
		//e->x = 5;
		//e->y =6;
		this->x = x;
		this->y = x;
	}
	int GetX()const
	{
		const Entity* e = this;//inside const function this is = const Entity*
	}
};

int main()

{
	Entity e1(1,2);
}
Posted by: Guest on August-10-2020

Browse Popular Code Answers by Language