C++ Programming Language Tutorials


Difference between dot(.) and arrow operator in C++


Arrow operator (->) : We have used arrow Operator in C++ multiple times it is also known as Class Member Access Operator is a combination of two different operators that is Minus operator (-) and greater than operator (>). It is used to access the public members of a class, structure, or members of union with the help of a pointer variable.

There is a .(dot) operator in C++ that is also used to access the members of a class. But .(dot operator) accesses the member or variable directly means without using the pointers whereas instead of accessing members directly the arrow operator(->) in C++ uses a pointer to access them. So the advantage of the -> operator is that it can deal with both pointer and non-pointer access but the dot(.) operator can only be used to access the members of a class.

 In Short we can say if you are using arrow operator then you have to create object of that class to use but in the case of dot operator you don't need to allocate memory and create object using new keyword and assign the address of created object to a pointer variable to use.

 

Example:

#include <iostream>

#include <string>

using namespace std;

class MyClass {       // The class

  public:             // Access specifier

    int myNum;        // Attribute (int variable)

    string myString;  // Attribute (string variable)

};

int main() {

  MyClass *myObj=new MyClass;  // Create an object of MyClass using new keyword

  MyClass obj2; // Created object using normal method

 

  // Access attributes and set values using pointer(arrow operator)

  myObj->myNum = 15;

  myObj->myString = "Some text";

  //Using Memeber access operator with object created without using new.

  //Using . operator

 

  obj2.myNum=16;

  obj2.myString="Using Class";

 

   // Print values

  cout << myObj->myNum << "\n";

  cout << myObj->myString<<endl;

 

  cout<<"using . operator"<<endl;

  cout<<obj2.myNum<<endl;

  cout<<obj2.myString<<endl;

  return 0;

}

---------------------------------------------------------OUTPUT--------------------------------------------------------


No comments:

Post a Comment