coderz.py

Keep Coding Keep Cheering!

Accessing data members

Accessing Elements

Members of a class can be accessed directly within the class by using their names. Accessing a member outside the class, on the other hand, is determined by its access specifier. The access specifier not only determines where the member is accessible in the program but also how it is accessible in the program.

Note: The dot(‘.’) operator with the object can be used to access the class’s data members and member functions.

Accessing Public Members:

Syntax:

obj_name.member_name;

where,

obj_name is the object name for the given class.

Example:
#include<iostream>
using namespace std;
class number {
 int x;
 public:
    int y;
    int z;
    void fn(int a);
} ;
  int main () {
     number p;
     p.y = 7;
     p.z = 2;
     p.x = 3;
     p.fn (10) ;
     return 0;
}

A class number with three data members, x, y, and z, is defined in this example. The data member x is set to private by default, whereas y and z are set to public. As a result, y and z can be accessed outside the class using the object name and the dot operator. However, because x is a private data member, it cannot be accessed directly from outside the class.

Accessing Private Members:

A class’s private members are not accessible outside the class, not even through the object name. They can, however, be accessed indirectly via the public member functions of that class.

Accessing Protected Data Members:

Protected data members can be accessed directly using the dot (.) operator within the current class’s subclass; for non-subclasses, we must follow the same steps as for private data members.

Note: also read about Access Modifiers in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement