Pointers in class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pointers in class

How to use the pointer to get the value of a variable in class? Is it possible? class myclass{ int a = 1; int* p = &a; }; int main(){ myclass a; cout << a.*p; // - error }

1st Mar 2017, 2:13 PM
Макс Елисеев (WMax)
Макс Елисеев (WMax) - avatar
3 Answers
+ 11
Your class variables are private and hence cannot be called directly by main function. Make them public by using the public access specifier. It is also generally not encouraged to initialise class variables during declaration.
1st Mar 2017, 2:18 PM
Hatsy Rei
Hatsy Rei - avatar
+ 11
// Well, this works. #include <iostream> using namespace std; class myclass{ public: myclass() { a = 1; p = &a; } int a; int *p; }; int main() { myclass a; cout << *(a.p); }
1st Mar 2017, 2:34 PM
Hatsy Rei
Hatsy Rei - avatar
0
I found something... but how it works? class myclass{ int speed = 1; }; int main(){ int Car::*pSpeed = &Car::speed; Car c1; c1.speed = 1; // direct access cout << "speed is " << c1.speed << endl; c1.*pSpeed = 2; // access via pointer to member cout << "speed is " << c1.speed << endl; }
1st Mar 2017, 2:24 PM
Макс Елисеев (WMax)
Макс Елисеев (WMax) - avatar