28 Sep C++ Operators
C++ Operators perform operations by taking one or more values, to give another value. These operations are performed on variables and values.
For example a + b, a – b, etc.
Scope Resolution Operator ::
Use this operator, if you want to access the global version of a variable. The global version remains the same throughout the program and the value remains the same even accessed from the inner block.
Here’s an example to easily understand the usage of the scope resolution operator,
On using the scope resolution operator, the global version of the variable “a” can be accessed i.e. a = 10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <conio.h> int a = 10; void main() { int a = 20; int b = 100; cout<< "Welcome to Studyopedia\n"; cout << "Value of variable a = " <<a<<"\n"; cout << "Value of variable a using scope resolution operator (::a) = " <<::a<<"\n"; cout << "Value of variable b = "<<b; getch(); } |
Here’s the output,
Note: Learn how to create a program and run it in Tubo C++
Memory Management Operators
Operators for managing memory in C++ include new() and delete(). These operators allocate and free the memory. The new() operator can also create an object. If you want to destroy an object, you can easily do it with delete().
new operator
Use the new operator to create objects of any type in C++. An object declared using new is alive till it is destroyed using the delete operator. The new operator can be overloaded.
Here’s how to declare,
1 2 3 |
int *a = new int; |
Here’s how you can initialize memory,
1 2 3 |
int *a = new int (15); |
The new operator can be used with array to create a memory space. Let’s see how,
1 2 3 |
int *a = new int [5]; |
delete operator
The delete operator is used to destroy objects created with the new operator,
Here’s how to declare,
1 2 3 |
delete a; |
The delete operator can be overloaded like the new operator.
Type Cast Operator
Explicit type conversion is possible with the typecast operator.
Here’s the syntax,learn h
1 2 3 |
type (expression) |
Here’s an example,
1 2 3 |
float (i) |
Memory Dereferencing Operators
The major difference between C and C++ is that C++ has classes. C++ allows defining a class that consists of data and members. So, in C++ you can also access the members through pointers, using the member dereferencing operators.
::* Declare a pointer to a member of a class
* Accessing a member using an object name and a pointer to that member.
->* Accessing a member using a pointer to the object and a pointer to that member.
No Comments