+ 3
this pointer only works within class.....not outside the class for calling the members?whyyyyy??
plz give me answer with detailed?
6 Answers
+ 2
The this pointer is a special pointer to refer to the object when inside it. Outside, just use the name of the object. For example, use myObj.myAttr instead of this->myAttr. Note that myAttr has to be public to be able to access it directly. Otherwise, you have to define getter and setter methods inside the class, like so:
class A{
private:
int myAttr;
public:
void setAttr(int n) {
this->myAttr = n;
}
int getAttr(void) {
return this->myAttr;
}
};
+ 1
set pointer to public variable
+ 1
can you give a small exemple...
+ 1
I think u need to understand d difference between a class and an object. All that code that you write is a class. it just serves as a structure.
class Vehicle {
int speed;
int tyres;
string model;
void accelerate();
. . .
}
what this class is: "a way to say, whenever you create a vehicle, it should have all these attributes and properties", . . . a blueprint (please, check the dictionary). Now, the individual entities you will create with this class are wat u refer to as objects.
Vehicle car1 = new Vehicle();
Vehicle car2 = new Vehicle();
Now, u had two distinct objects, u can create as many objects as you require from that single class declaration. The "this" pointer works distinctively within each object.
0
or change variable private to public
0
this pointer is used solely to point to object it self within the class.
u don't need it outside as u have object name .
static methods don't have this variable in obj as they are not part of object but are part of class
use of this pointer by below example
eg:
class A{
int I;
public:
void setI(int i)
{
this.i=i
}
};
here if we haven't used this, the i variable in class will not have been set. as it will try to set local I variable with local I variable in the method.