I am new to c++.I was told the structures and the classes are almost the same.The main differece is classes in c++ are by default private while structures are public.
I have two different codes where we use pointers to structure members and classe members.
struct Simple { int a; };
int main() {
Simple so, *sp = &so;
sp->a;
so.a;
}
We use pointers to struct members in the above way.
Why do we have to use the pointers to class members int he following way?
class X {
public:
int a;
void f(int b) {
cout << "The value of b is "<< b << endl;
}
};
int main() {
// declare pointer to data member
int X::*ptiptr = &X::a;
int X::*ptiptr1 = &X::a;
// create an object of class type X
X xobject,xobject1;
// initialize data member
xobject.*ptiptr = 10;
xobject->*ptiptr1 = 11;
}
Why are we first declaring a pointer to the class data member? Why can't we do it like we have done for structures?
Please help me out.Thanks.
You're doing two very different things here.
The first is creating a normal object pointer to one particular object. This refers to that object, and can be used to access any of its members.
The second creates a pointer-to-member, which is very different to an object pointer. It refers to a class member and not a particular object, and can be applied to any object to access that member.
In either case, it's irrelevant whether the class is defined using the class
or struct
keyword. That only affects whether members default to being private or public.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments