Arrow Operator
Posted on April 1, 2023 • 3 minutes • 449 words
We can create a pointer variable for Complex data types such as struct and class. Also we can create a pointer for class and struct in stack and heap As similar as primitive data types.
Syntax
className *pointerName;
pointerName = &classObjectName;
Example
struct Student
{
int mark;
std::string name;
};
int main(int argc, char const *argv[])
{
Student s;
s.mark = 10;
s.name = "ANOOP";
Student *sPtr = &s;
}
Accessing data members using pointer:
We can access data members of a struct/class pointer variable by using *
operator with .
operator
Syntax
(*pointerName).memberVariableName
Example
int main(int argc, char const *argv[])
{
Student s;
s.mark = 10;
s.name = "ANOOP";
Student *sPtr = &s;
std::cout << (*sPtr).mark << "," << (*sPtr).name << std::endl;
}
When it comes to structure and classes, we need to use * (star) and . (dot) operators in combination.
As a result, C++ introduced a new operator called -> (arrow-operator) to access class and structure members.
Syntax
pointerName->memberVariableName
Example
int main(int argc, char const *argv[])
{
Student s;
s.mark = 10;
s.name = "ANOOP";
Student *sPtr = &s;
std::cout << sPtr->mark << "," << sPtr->name << std::endl;
}
new Operator for Constructors.
We also can use new operator for Parameterized constructors.
Syntax
ClassName *pointerName = new ClassName(arguments);
Example
#include<iostream>
class Rectangle
{
public:
Rectangle(int len,int wid)
{
length = len;
width = wid;
}
int getArea()
{
return length * width;
}
int length,width;
};
int main(int argc, char const *argv[])
{
Rectangle *rPtr = new Rectangle(20,30);
std::cout << "Area 2 : " << rPtr->getArea() << std::endl;
delete rPtr;
}
Full Example
#include<iostream>
struct Student
{
int mark;
std::string name;
};
void myFunc1()
{
Student s;
s.mark = 10;
s.name = "ANOOP";
Student *sPtr = &s;
std::cout << (*sPtr).mark << "," << (*sPtr).name << std::endl; // ->
std::cout << sPtr->mark << "," << sPtr->name << std::endl;
}
void myFunc2()
{
Student *sPtr = new Student();
sPtr->mark = 100;
sPtr->name = "anoop";
std::cout << (*sPtr).mark << "," << (*sPtr).name << std::endl;
std::cout << sPtr->mark << "," << sPtr->name << std::endl;
}
// ----------------------------------------------------
class Rectangle
{
public:
Rectangle(int len,int wid)
{
length = len;
width = wid;
}
int getArea()
{
return length * width;
}
int length,width;
};
void myFunc3()
{
Rectangle r1(10,20);
Rectangle *rPtr = &r1;
std::cout << "Area : " << rPtr->getArea() << std::endl;
Rectangle *rPtr2 = new Rectangle(20,30);
std::cout << "Area 2 : " << rPtr2->getArea() << std::endl;
delete rPtr2;
std::cout << "Area 2 : " << rPtr2->getArea() << std::endl;
}
int main(int argc, char const *argv[])
{
myFunc1();
myFunc2();
myFunc3();
return 0;
}