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.
Syntax:
obj_name.member_name;
where,
obj_name is the object name for the given class.
#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.
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.
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++
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…