C++ Accessing Class Members
In C++, you can access the members of a class using the dot (.) or arrow (->) operator, depending on whether you have a reference or a pointer to the object.
Here's an example class definition:
class MyClass { public: int publicVar; private: int privateVar; public: void setPrivateVar(int value) { privateVar = value; } int getPrivateVar() { return privateVar; } };
In this example, we've defined a class called MyClass
with a public member variable publicVar
and a private member variable privateVar
. We've also defined two public methods to set and get the private variable.
To access the public variable publicVar
, you can use the dot operator with an object of the class:
MyClass obj; obj.publicVar = 42;
In this example, we've created an object of the MyClass
class and set the value of its public variable publicVar
to 42 using the dot operator.
To access the private variable privateVar
, you need to use the public methods setPrivateVar()
and getPrivateVar()
:
MyClass obj; obj.setPrivateVar(10); int privateVarValue = obj.getPrivateVar();
In this example, we've created an object of the MyClass
class and used the setPrivateVar()
method to set the value of its private variable privateVar
to 10. We've then used the getPrivateVar()
method to retrieve the value of the private variable into the privateVarValue
variable.
Note that when using a pointer to an object of the class, you need to use the arrow operator (->) to access its members:
MyClass* ptr = new MyClass(); ptr->publicVar = 42; ptr->setPrivateVar(10); int privateVarValue = ptr->getPrivateVar(); delete ptr;
In this example, we've created a pointer to an object of the MyClass
class using the new
keyword and set the value of its public variable publicVar
to 42 using the arrow operator. We've also used the setPrivateVar()
method and getPrivateVar()
method to access the private variable, again using the arrow operator. Finally, we've deleted the object using the delete
keyword to free the memory allocated on the heap.