×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Class Member Access Operator in C++ programming language

Learn: What is Class Member Access Operator in C++ programming language, how to access public members (data members/member functions) in C++ using object?

What is Class Member Access Operator in C++?

Dot (.) operator is known as "Class Member Access Operator" in C++ programming language, it is used to access public members of a class. Public members contain data members (variables) and member functions (class methods) of a class.

Syntax

object_name.member_name;

declaration

Consider the given class declaration

class sample {
 private:
  int a;

 public:
  int b;
  void init(int a) { this->a = a; }
  void display() { cout << "a: " << a << endl; }
};

In this class declaration, following are the class members that can be accessed through the "Class Member Access Operator":

Public data member: b

Public member functions: init(), display()

Example of Class Member Access Operator

Consider the below example demonstrating the real use of class access member operator in C++:

#include <iostream>
using namespace std;

class sample {
 private:
  int a;

 public:
  int b;
  void init(int a) { this->a = a; }
  void display() { cout << "a: " << a << endl; }
};

int main() {
  // object declaration
  sample sam;
  // value assignment to a and back
  sam.init(100);
  sam.b = 200;

  // printing the values
  sam.display();
  cout << "b: " << sam.b << endl;

  return 0;
}

Output

a: 100
b: 200

Explanation

Consider the following statements in main() function

  • sam.init(100); - This statement will assign 100 to the private data member a through this public member function.
  • sam.b=200; - This statement will assign 200 to the public data member b.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.