C++ Operators

Operators are symbols which take one or more operands or expressions and perform arithmetic or logical computations.
C++ supports all operators of C, C++ introduces some new operators given as below:

SymbolsName
<< Insertion operator.
>> Extraction operator.
:: Scope resolution operator.
::* Pointer-to-member declarator.
->* Pointer-to-member operator.
.* Pointer-to-member operator.
new Dynamic memory allocation operator.
delete Memory release operator.

Scope Resolution Operator (SRO) ::

:: (scope resolution) operator is used to qualify hidden names so that you can still use them.
:: (SRO) can be used two types:

  1. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class.
  2. You can also use the class scope operator to qualify class names or class member names. If a class member name is hidden, you can use it by qualifying it with its class name and the class scope operator.
    Use of unary SRO:
    :: variable_name;
    Use as class scope (to access class member):
    class_name :: class_member;
// Program to illustrate :: (SRO operator)
#include <iostream.h>
int var=100;	// Global variable

int main()
{
	int var=200;
	cout<<"value of var (local) : "<<var<<endl;
	cout<<"value of var (Global): "<<::var<<endl;
	
	::var=::var+20;	// updating global value
	var=var+20;		// updating local value 

	cout<<"\nAFTER UPDATING VALUES\n";
	cout<<"value of var (local) : "<<var<<endl;
	cout<<"value of var (Global): "<<::var<<endl;
	return 0;
}

Output

value of var (local) : 200
value of var (Global): 100

AFTER UPDATING VALUES
value of var (local) : 220
value of var (Global): 120

Program to illustrate :: (SRO operator) with class

#include <iostream.h>
class sample{
	public:
		static int count;
};

int sample::count =100;
int main(){
	cout<<"Value is = "<<sample::count<<endl;
	sample::count+=1;
	cout<<"AFTER UPDATING..........\n";
	cout<<"Value is = "<<sample::count<<endl;
	return 0;
}

Output

Value is = 100
AFTER UPDATING..........
Value is = 101



Member dereferencing operator

C++ permits to access the class member functions through pointer, to achieve this functionality ( accessing class member through a pointer), C++ provides the set of these three operators to declare and access.

Pointer-to-member declarator [::*]:

is used to declare a pointer of member function.
To access the class member function using pointer, you must declare the pointer of that function.

    Return_Type (Class_Name::* pointer_name) (Argument_List)= & class_name::fun_name;
Pointer-to-member operator [.*]:

is used to access member function thorugh pointer, ( if class object is not a pointer)

Pointer-to-member operator [->*]:

is used to access member function thorugh pointer, ( if class object is a pointer)

    (Object_Name .*Pointer_Fun_Name)([Argument_List]);
(Pointer_Object_Name ->*Pointer_Fun_Name)([Argument_List]);
#include <iostream.h>
class Sample
{
    private:
        int a;
    public :
        Sample(int a)    //constructor
        {
	        this->a=a;
        }
        int fun(void)
        {
	        cout<<"\nBody of fun (class Sample), value of a= "<< a << endl;
	        return 0;
        }
};

int main()
{
    Sample Obj(100),*PObj;
    PObj=&Obj;
    // declaration of pointer to member function..
    int (Sample::*ptrFun)(void);
    // initialization of pointer to member function
    ptrFun=&Sample::fun;

    // access using simple object
    (Obj.*ptrFun)();
    // access using pointer object
    (PObj->*ptrFun)();
    return 0;
}

Output

Body of fun (class Sample), value of a= 100
Body of fun (class Sample), value of a= 100


new and delete Operators

new is used to allocate memory for a variable, object, array, array of objects.. etc at run time. "To declaring memory at run time is known as dynamic memory allocation." we use memory by this method (dynamic allocation) when it is not known in advance how much memory space is needed.

since "these operators manipulate memory on the free store, so they are also known as free store operators.

the new operator can be used to create objects of any type, it takes the following general form:

    pointer_variable = new data_type;

Here, pointer_variable is a variable that store the starting address of allocating memory space.

// Program to illustrate new ..
#include <iostream.h>
int main(){
	int  *age=new int;
	char *gender=new char;
	*age=0;			// assigning default value (not necessary) 
	*gender='M';	// assigning default value (not necessary)
	// taking input through keyboard
	cout<<"Enter your age ? :";
	cin>> (*age);
	cout<<"AGE IS : "<< *age <<",GENDER IS : "<< *gender << endl;
	return 0;
}

Output

Enter your age ? :23
AGE IS : 23,GENDER IS : M



delete Operator :

delete operator is used to Deallocates the dynamically allocated memory.

Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete.

delete takes the following general form:

    1. delete pointer_variable;
    2. delete []pointer_variable;

The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements.

// Program to declare dynamic array of integers...
#include <iostream.h>
int main(){
    int *array;		// declaration
    int max,i;

    cout<<"Enter total number of elements :";
    cin>>max;

    // declare memory @ run time to max element...
    array=new int[max];

    // read values 
    cout<<"Enter array elements:\n";
    for(i=0;i< max;i++){
	    cout<<"Element "<< i+1 <<": ";
	    cin>> array[i];
    }

    cout<<"Elements are : ";
    for(i=0;i< max;i++){
	    cout<< array[i] <<"\t";
    }
    // release dynamically allocated space
    delete []array;
    cout<< endl;
    return 0;
}

Output

Enter total number of elements :5
Enter array elements:
Element 1: 111
Element 2: 222
Element 3: 333
Element 4: 444
Element 5: 555
Elements are : 111      222     333     444     555

Note******* after releasing memory, pointer_variable does not destroy, only allocated block of memory destroyed.

consider the following code:

delete []array;
cout<<"\nElements are (after releasing memory):\n";
for(i=0;i< max;i++){
	cout<< array[i] <<"\t";
}

Output

Enter total number of elements :5
Enter array elements:
Element 1: 111
Element 2: 222
Element 3: 333
Element 4: 444
Element 5: 555
Elements are : 111      222     333     444     555
Elements are (after releasing memory):
-572662307     -572662307      -572662307      -572662307      -572662307


delete Operator for 2-D Array :

We can declare a 2-D array using new operator.
it takes the following general form:

pointer_variable= new data-type[max_row*max_col];

here max_row is maximum number of rows and max_col is maximum number of cols.

Note that the earlier expression of X[i][j] has been replaced by X[i*c+j].

where c represents the maximum number of columns in the 2-D array X.

//Declare 2-D array using new operator

#include <iostream.h>

int main(){
	int *arr;
	int rows,cols,i,j;

	cout<<"Enter rows ?:";
	cin>>rows;
	cout<<"Enter cols ?:";
	cin>>cols;

	// declare 2-D array
	arr=new int[rows*cols];
	
	// read value 
	cout<<"Enter elements ..\n";
	for(i=0;i< rows;i++){
		for(j=0;j< cols;j++){
			cout<<"Enter value ? :";
			cin>>arr[i*cols+j];
		}
	}
	
	// print in matrix format 
	cout<<"Entered elements are :\n";
	for(i=0;i< rows;i++){
		for(j=0;j< cols;j++){
			cout<< arr[i*cols+j]<<"\t";
		}
		cout<< endl;
	}
    return 0;
}



Comments and Discussions!

Load comments ↻





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