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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…