+ 3

this pointer only works within class.....not outside the class for calling the members?whyyyyy??

plz give me answer with detailed?

13th Sep 2016, 10:00 PM
Bint E Asif
Bint E Asif - avatar
6 Respuestas
+ 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; } };
14th Sep 2016, 12:39 PM
Zen
Zen - avatar
+ 1
set pointer to public variable
14th Sep 2016, 3:42 AM
Muhammad khalil
Muhammad khalil - avatar
+ 1
can you give a small exemple...
14th Sep 2016, 4:39 AM
Bint E Asif
Bint E Asif - avatar
+ 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.
7th Nov 2016, 11:39 PM
Daniel Adesubomi Oniya
Daniel Adesubomi Oniya - avatar
0
or change variable private to public
14th Sep 2016, 3:43 AM
Muhammad khalil
Muhammad khalil - avatar
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.
21st Oct 2016, 9:51 PM
PANKAJ KUMAR
PANKAJ KUMAR - avatar