Home > Net >  How to get a user's input into a class's member variable and dereference it
How to get a user's input into a class's member variable and dereference it

Time:09-09

class cookie{
public:
    cookie() = default;
    int*p_member{};
    int case{};
private:
};

#include <iostream>
using namespace std;
int main(){
    cookie cold;
    cout << "Type what you want into the cookie p_member variable " << endl;
    std::cin >> cold.*p_member; // this doesn't work 
}

I wanna know how to get access to the classes pointer variable put data inside it and then derefrence it.

CodePudding user response:

First things first, make sure that you're not dereferencing a null or uninitialized pointer. Otherwise you'll have undefined behavior.


it's about a member that is a pointer.I would like to assign a value to the member, and then dereference the member so i could print it out.

You can use a pointer to member syntax for this task as shown below:

class cookie{
public:
    
    int var;
    int cookie::*p_member=&cookie::var; //p_member can point to an int data member of an cookie object 
    
};

int main(){
    cookie cold{};
    
    cout << "Type what you want into the cookie p_member variable " << endl;
    std::cin >> cold.*cold.p_member;  //take input from user directly into var using member pointer syntax
    
    std::cout << "var: " << cold.var << std::endl; //print var to confirm that it is correctly set
}

Working demo

  • Related