Categories: C++

Accessing data members

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

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago