class member variable pointer? When do you use it?

Asked 2 years ago, Updated 2 years ago, 101 views

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
    return 0;
}

I saw this code, and I wonder when int Car::*pSpeed=&Car::speed; is used in main.

c++ class pointer

2022-09-22 08:22

1 Answers

It is called pointer to member. It allows you to approach member variables in a roundabout way.

For more information, I have added more code below and annotated it.

#include <iostream>
using namespace std;

class Car
{
    public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;

    Car c1;
    c1.speed = 1; // Direct access (typical)
    cout << "speed is" << c1.speed << endl; //1 output
    c1.*pSpeed = 2; // use pointer to member to approach (pass)
    cout << "speed is" << c1.speed << endl; //2 output
    return 0;
}

I only know it as a theory, but I've never actually written it.


2022-09-22 08:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.