I have a struct with two members, for example:
struct DataSet {
    int x;
    int y;
};
..., and i have to access those in a method, but only one at a time, for example:
void foo(StructMember dsm) { // ("StructMember" does not exist)
    DataSet ds;
    ds.x = 4;
    ds.y = 6;
    std::cout << ds.dsm * ds.dsm << std::endl;
}
foo(x);
foo(y);
Output i wish to have:
16
36
What should I do when I have to solve a problem like this? Is there a data type which can access a member?
Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures. Nested Structures are allowed in C Programming Language.
Structure members are accessed using dot (.) operator.
An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union.
A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C. The general consensus seems to be that the former can be applied to small structs without penalty in most cases.
Yes, you can use a pointer-to-member. The syntax for the type is TypeOfMember TypeOfStruct::*, and to access you do struct_variable.*pointer_variable
using StructMember = int DataSet::*;  // Pointer to a member of `DataSet` of type `int`
void foo(StructMember dsm) {
    DataSet ds;
    ds.x = 4;
    ds.y = 6;
    std::cout << ds.*dsm * ds.*dsm << std::endl;
}
int main() {
    foo(&DataSet::x);
    foo(&DataSet::y);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With