C++ Pointer Operator

In this chapter we are going to study C++ Pointer Operators. C++ provides two pointer operators one is value at operator or indirection operator and address operator.

C++ Pointer Operator

C++ Pointer Operator

C++ Address of Operator (&)

  1. The & is a unary operator means it requires only one operand.
  2. The Address of Operator returns the memory address of its operand.
  3. Address of operator has the same precedence and right-to-left associativity as that of other unary operators.
  4. Symbol for the bitwise AND and the address of operator are the same but they don’t have any connection between them

C++ Address Operator

C++ Program : Address of Operator

#include<iostream>
using namespace std;
int main()
{
   int num=10;
   cout << "Value of number   : " << num << endl;
   cout << "Address of number : " << &num << endl;
}

Output :

Value of number : 10
Address of number : 0xffad72dc

Summary

PointExplanation
OperatorAddress of
TypeUnary Operator
Operates onSingle Operand
ReturnsAddress of the operand
Associativityright-to-left
ExplanationAddress of operator gives the computer's internal location of the variable.

C++ Indirection Operator *

  1. The Indirection operator * is a unary operator means it requires only one operand.
  2. Indirection Operator (*) is the complement of Address of Operator (&).
  3. Indirection Operator returns the value of the variable located at the address specified by its operand.

C++ Program : Indirection Operator

#include<iostream>
using namespace std;
int main()
{
   int num=10;
   int *ptr;
   ptr=&num;
   cout << " num = " << num << endl;
   cout << " &num = " << &num << endl;
   cout << " ptr = " << ptr << endl;
   cout<< " *ptr = " << *ptr << endl;
}

Output :

num = 10
# = 0xffcc2bd8
ptr = 0xffcc2bd8
*ptr = 10

Calculations:

// Sample Code for Dereferencing of Pointer
*(ptr) = value at (ptr)
       = value at (0xffcc2bd8) 
       = 10
//Address in ptr is nothing but address of num

Summary

PointExplanation
OperatorIndirection Operator
TypeUnary Operator
Operates onSingle Operand
ReturnsValue at address of the operand)
Associativityright-to-left

Though multiplication symbol and the “Indirection Operator” symbol are the same still they don’t have any relationship between each other.

Both & and * have a higher precedence than all other arithmetic operators except the unary minus/plus, with which they share equal precedence.

C++ Conditional Operator

Conditional Operator [?:] : Ternary Operator in C++

  1. Conditional operators are also called as Ternary Operator.
  2. They are represented by ?:
  3. Ternary Operator takes on 3 Arguments.

Syntax of Ternary Operator:

Expression_1 ? Expression_2 : Expression_3

where

  • Expression_1 is Condition
  • Expression_2 is statement followed if Condition is True
  • Expression_3 is statement followed if Condition is False
  • Explanation of syntax:

    1. Expression_1 is a condition so it will return the result either True or False.
    2. If result of expression_1 is True that is NON-ZERO, then Expression_2 is Executed.
    3. If result of expression_1 is False that is ZERO, then Expression_3 is Executed.

    Program 1#: Conditional Operator Program

    Let us take the simple example of finding greater number from two given numbers using Conditional Operator.

    #include<iostream>
    using namespace std;
    int main()
    {
       int num1=10;
       int num2=20;
       num1>num2 ? cout << "num1 is greater than num2" : cout<< "num2 is greater than num1" ;
       return 0;
    }
    

    Output:

    num2 is greater than num1
    

    C++ sizeof Operator

    C++ sizeof Operator

    • sizeof is a compile-time operator used to calculate the size of data type or variable.
    • sizeof operator will return the size in integer format.
    • sizeof is a keyword.
    • sizeof operator can be nested.

    Syntax of sizeof Operator:

    sizeof(data type)
    

    Data type include variables, constants, classes, structures, unions, or any other user defined data type.

    Examples of sizeof operator:

    Size of Data Types

    #include <iostream>
    using namespace std;
    int main()
    {
       cout << "Size of int : " << sizeof(int) << endl;
       cout << "Size of long int : " << sizeof(long int) << endl;
       cout << "Size of float : " << sizeof(float) << endl;
       cout << "Size of double : " << sizeof(double) << endl;
       cout << "Size of char : " << sizeof(char) << endl;
       return 0;
    }
    

    Output:

    Size of int : 4
    Size of long int : 4
    Size of float : 4
    Size of double : 8
    Size of char : 1
    

    Size of Variables:

    #include <iostream>
    using namespace std;
    int main()
    {
       int i;
       char c;
       cout << "Size of variable i : " << sizeof(i) << endl;
       cout << "Size of variable c : " << sizeof(c) << endl;
       return 0;
    }
    

    Output:

    Size of variable i : 4
    Size of variable c : 1
    

    Size of Constant:

    #include <iostream>
    using namespace std;
    int main()
    {
       cout << "Size of integer constant: " << sizeof(10) << endl;
       cout << "Size of character constant : " << sizeof('a') << endl;
       return 0;
    }
    

    Output:

    Size of integer constant: 4
    Size of character constant : 1
    

    Nested sizeof operator:

    #include <iostream>
    using namespace std;
    int main()
    {
       int num1,num2;
       cout << sizeof(num1*sizeof(num2));
         return 0;
    }
    

    Output:

    4
    

    C++ Destructor Basics

    In the previous chapter we have learnt about the C++ constructors and basic type of constructors. In this chapter we will be learning about C++ Destructor Basics

    C++ Destructor Basics

    1. Destructors are special member functions of the class required to free the memory of the object whenever it goes out of scope.
    2. Destructors are parameterless functions.
    3. Name of the Destructor should be exactly same as that of name of the class. But preceded by ‘~’ (tilde).
    4. Destructors does not have any return type. Not even void.
    5. The Destructor of class is automatically called when object goes out of scope.

    C++ Destructor programs

    C++ Destructor Program #1 : Simple Example

    #include<iostream> 
    using namespace std;
    class Marks
    {
    public:
       int maths;
       int science;
       //constructor
       Marks() {
          cout << "Inside Constructor"<<endl;
          cout << "C++ Object created"<<endl;
       }
       //Destructor
       ~Marks() {
          cout << "Inside Destructor"<<endl;
          cout << "C++ Object destructed"<<endl;
       }
    };
    int main( )
    {
       Marks m1;
       Marks m2;
       return 0;
    }
    

    Output

    Inside Constructor
    C++ Object created
    Inside Constructor
    C++ Object created
    Inside Destructor
    C++ Object destructed
    Inside Destructor
    C++ Object destructed
    

    Explanation :

    You can see destructor gets called just before the return statement of main function. You can see destructor code below -

    ~Marks() {
       cout << "Inside Destructor"<<endl;
       cout << "C++ Object destructed"<<endl;
    }
    

    C++ Destructor always have same name as that of constructor but it just identified by tilde (~) symbol before constructor name.

    Below example will show you how C++ destructor gets called just before C++ object goes out of scope.

    C++ Destructor Program #2 : Out of scope

    #include<iostream> 
    using namespace std;
    class Marks
    {
    public:
       int maths;
       int science;
       //constructor
       Marks() {
          cout << "Inside Constructor"<<endl;
          cout << "C++ Object created"<<endl;
       }
       //Destructor
       ~Marks() {
          cout << "Inside Destructor"<<endl;
          cout << "C++ Object destructed"<<endl;
       }
    };
    int main( )
    {
       {
       Marks m1;
       }
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       return 0;
    }
    

    Output :

    Inside Constructor
    C++ Object created
    Inside Destructor
    C++ Object destructed
    Hello World !!
    Hello World !!
    Hello World !!
    Hello World !!

    Explanation :

    In this example we have defined the scope of the object as we declared object inside the curly braces i.e inside the inner block.

    int main( )
    {
       {
       Marks m1;
       }
    

    So object will be accessible only inside the curly block. Outside the curly block we cannot access the object so destructor gets called when inner curly block ends

    In this example Hello World !! gets printed after the destructor. however for below example Hello World !! gets printed before constructor

    C++ Destructor Program #3 : before destructor

    #include<iostream> 
    using namespace std;
    class Marks
    {
    public:
       int maths;
       int science;
       //constructor
       Marks() {
          cout << "Inside Constructor"<<endl;
          cout << "C++ Object created"<<endl;
       }
       //Destructor
       ~Marks() {
          cout << "Inside Destructor"<<endl;
          cout << "C++ Object destructed"<<endl;
       }
    };
    int main( )
    {
       Marks m1;
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       cout<<"Hello World !!" <<endl;
       return 0;
    }
    

    Output :

    Inside Constructor
    C++ Object created
    Hello World !!
    Hello World !!
    Hello World !!
    Hello World !!
    Inside Destructor
    C++ Object destructed

    C++ Bitwise Operators

    In this section we are going to study C++ Bitwise operator, its importance and basic operating principle.

    C++ Programming Bitwise Operators:

    • In programming, unlike byte level operations, we may need to do bit level calculations by operating on the individual data bit.
    • C++ gives us various bitwise operators for manipulation of bits.
    • C++ Bitwise Operators operates on Integer and character data types only.
    • C++ Bitwise Operators does not operates on float, double.
    • There are 6 Bitwise Operators in C++.

    List of Bitwise Operators

    Operator Name of Operator
    ~ One's Compliment
    gt;gt; Right Shift
    lt;lt; Left Shift
    amp; Bitwise AND | Bitwise OR ^ Bitwise XOR

    Examples of Bitwise Operators:

    One's Compliment (~) Operator:

    This operator is generally used to turn ON or turn OFF bit.

    #include <iostream>
    using namespace std;
    int main()
    {
       // 12 = 0000 1100
       unsigned int num1 = 12
       int num2 = 0;           
       num2 = ~num1;  
       cout << "Value of num2 is: " << num2 << endl ;
       return 0;
    }
    

    Output:

    Value of num2 is: -13
    

    Right Shift (>>) Operator:

    This operator is used to shift the bits to right by position specified in the expression.

    #include <iostream>
    using namespace std;
    int main()
    {
       unsigned int num1 = 12; // 12 = 1100 
       int num2 = 0;           
       num2 = num1 >> 2; // 3 = 0011
       cout << "Value of num2 is: " << num2 << endl ;
       return 0;
    }
    

    Output:

    Value of num2 is: 3
    

    Left Shift (<<) Operator:

    This operator is used to shift the bits to left by position specified in the expression.

    #include <iostream>
    using namespace std;
    int main()
    {
       unsigned int num1 = 12; // 12 = 0000 1100 
       int num2 = 0;           
       num2 = num1 << 2; // 48 = 0011 0010
       cout << "Value of num2 is: " << num2 << endl ;
       return 0;
    }
    

    Output:

    Value of num2 is: 48
    

    Bitwise AND (&):

    This operator is generally used to mask particular part of byte.

    Output:

    Value of num2 is: 8
    
    #include <iostream>
    using namespace std;
    int main()
    {
       unsigned int num1 = 10;	  // 10 = 0000 1010  
       unsigned int num2 = 12;	  // 12 = 0000 1100
       int num3 = 0;           
       num3 = num1 & num2;         // 8 = 0000 1000
       cout << "Value of num3 is : " << num3 << endl ;
       return 0;
    }
    

    Bitwise OR (|):

    #include <iostream>
    using namespace std;
    int main()
    {
       unsigned int num1 = 10;	  // 10 = 0000 1010  
       unsigned int num2 = 12;	  // 12 = 0000 1100
       int num3 = 0;           
       num3 = num1 | num2;         // 14 = 0000 1110
       cout << "Value of num3 is : " << num3 << endl ;
       return 0;
    }
    

    Output:

    Value of num2 is: 14
    

    Bitwise XOR (^):

    #include <iostream>
    using namespace std;
    int main()
    {
       unsigned int num1 = 10;  // 10 = 0000 1010  
       unsigned int num2 = 12;  // 12 = 0000 1100
       int num3 = 0;           
       num3 = num1 ^ num2;      // 6 = 0000 0110
       cout << "Value of num3 is : " << num3 << endl ;
       return 0;
    }
    

    Output:

    Value of num2 is: 6
    

    C++ Assignment Operator

    C++ assignment Operator basics

    1. Assignment Operator is used to assign value to an variable.
    2. Assignment Operator is denoted by equal to (=) sign.
    3. This operator copies the value at the right side of the operator into the left side variable.
    4. Assignment Operator is binary operator.
    5. Assignment Operator has higher precedence than comma operator only.
    6. Assignment Operator has lower precedence than all other operators except comma operator.

    Ways of Using Assignment Operator:

    In this section we are going to see different ways in which Assignment Operator can be used.

    Assignment Operator used to Assign Value

    In this case the particular value or result of particular expression is assigned to the variable.

    #include<iostream>
    using namespace std;
    int main()
    {
       int value;
       value=10;
       return 0;
    }
    

    In this example, 10 is assigned to variable value.

    Assignment Operator used to Type Cast

    #include<iostream>
    using namespace std;
    int main()
    {
       int value;
       value=10.5;
       cout<<value;
       return 0;
    }
    

    Higher values can be type cast to lower values using assignment operator. It can also cast lower values to higher values.

    Shorthand assignment operator:

    Operator Symbol Name of OperatorExample Equivalent Construct
    +=Addition assignment a+=5 a=a+5
    -=Subtraction assignment a-=5 a=a-5
    *=Multiplication assignment a*=5 a=a*5
    /=Division assignment a/=5 a=a/5
    %=Remainder assignment a%=5 a=a%5

    Example:

    #include <iostream>
    using namespace std;
    int main()
    {
       int num = 10;
       num+=5 ;
       cout << "Result of Expression 1 = " <<num<< endl ;
       num = 10;
       num-=5 ;
       cout << "Result of Expression 2 = " <<num<< endl ;
       num = 10;
       num*=5 ;
       cout << "Result of Expression 3 = " <<num<< endl ;
       num = 10;
       num/=5 ;
       cout << "Result of Expression 4 = " <<num<< endl ;
       num = 10;
       num%=5 ;
       cout << "Result of Expression 5 = " <<num<< endl ;
       return 0;
    }
    


    Output:

    Result of Expression 1 = 15
    Result of Expression 2 = 5
    Result of Expression 3 = 50
    Result of Expression 4 = 2
    Result of Expression 5 = 0
    

    C++ Logical Operator

    In this tutorial we will study C++ logical operator in detail. C++ logical operators are used mostly inside the condition statement such as if,if…else where we want multiple conditions.

    C++ Logical Operator

    1. Logical Operators are used if we want to compare more than one condition.
    2. Depending upon the requirement, proper logical operator is used.
    3. Following table shows us the different C++ operators available.
    Operators Name of the Operator Type
    && AND Operator Binary
    || OR Operator Binary
    ! NOT Operator Unary

    According to names of the Logical Operators, the condition satisfied in following situation and expected outputs are given

    Operator Output
    AND Output is 1 only when conditions on both sides of Operator become True
    OR Output is 0 only when conditions on both sides of Operator become False
    NOT It gives inverted Output

    Let us look at all logical operators with example-

    C++ Program : Logical Operator

    #include<iostream>
    using namespace std;
    int main()
    {
       int num1=30;
       int num2=40;
       if(num1>=40 || num2>=40)
          cout<<"OR If Block Gets Executed"<<endl;
       if(num1>=20 && num2>=20)
          cout<<"AND If Block Gets Executed"<<endl;
       if(!(num1>=40))
          cout<<"NOT If Block Gets Executed"<<endl;
       return 0;
    }
    

    Output:

    OR If Block Gets Executed
    AND If Block Gets Executed
    NOT If Block Gets Executed
    

    Explanation of the Program

    Or statement gives output = 1 when any of the two condition is satisfied.

    if(num1>40 || num2>=40)
    

    Here in above program , num2=40. So one of the two conditions is satisfied. So statement is executed.

    For AND operator, output is 1 only when both conditions are satisfied.

    if(num1>=20 && num2>=20)
    

    Thus in above program, both the conditions are True so if block gets executed.

    Truth table

    Operator 1st Condition 2nd Condition Output
    AND True True True
    True False False
    False True False
    False False False
    OR True True True
    True False True
    False True True
    False False False
    NOT True - False
    False - True

    C++ Relational Operators

    C++ Relational operators specify the relation between two variables by comparing them. There are 5 relational operators in C

    C++ Relational Operators

    In C++ Programming, the values stored in two variables can be compared using following operators and relation between them can be determined.

    Various C++ relational operators available are-

    Operator, Meaning
    > ,Greater than
    >= , Greater than or equal to
    == , Is equal to
    != , Is not equal to
    < , Less than or equal to <= , Less than [/table]

    Relational Operator Programs

    Program #1: Relational Operator Comparison

    As we discussed earlier, C++ Relational Operators are used to compare values of two variables. Here in example we used the operators in if statement.

    Now if the result after comparison of two variables is True, then if statement returns value 1.

    And if the result after comparison of two variables is False, then if statement returns value 0.

    #include<iostream>
    using namespace std;
    int main()
    {
       int a=10,b=20,c=10;
       if(a>b)
          cout<<"a is greater"<<endl;
       if(a<b)
          cout<<"a is smaller"<<endl;
       if(a<=c)
          cout<<"a is less than/equal to c"<<endl;
       if(a>=c)
          cout<<"a is less than/equal to c"<<endl;
       return 0;
    }
    

    Output

    a is smaller 
    a is less than/equal to c
    a is greater than/equal to c
    

    Program #2: Relational Operator Equality

    In C++ Relational operators, two operators that is == (Is Equal to) and != (is Not Equal To), are used to check whether the two variables to be compared are equal or not.

    Let us take one example which demonstrate this two operators.

    #include<iostream>
    using namespace std;
    int main()
    {
       int num1 = 30;
       int num2 = 40;
       int num3 = 40;
       if(num1!=num2)
          cout<<"num1 Is Not Equal To num2"<<endl;
       if(num2==num3)
          cout<<"num2 Is Equal To num3"<<endl;
       return(0);
    }
    

    Output

    num1 Is Not Equal To num2
    num2 Is Equal To num3
    

    C++ Constructor basic concept

    In this tutorial we will learnt about C++ constructor basic concept. Tutorial explains you everything about constructor in C++ in easier language.

    C++ Constructor basic concept

    1. C++ constructors are the special member function of the class which are used to initialize the objects of that class
    2. The constructor of class is automatically called immediately after the creation of the object.
    3. Name of the constructor should be exactly same as that of name of the class.
    4. C++ constructor is called only once in a lifetime of object when object is created.
    5. C++ constructors can be overloaded
    6. C++ constructors does not return any value so constructor have no return type.
    7. C++ constructor does not return even void as return type.

    C++ Constructor Types

    1. Default Constructor
    2. Parametrized Constructor
    3. Copy Constructor

    We will discuss different C++ constructor types in detail -

    C++ Constructor Types #1 : Default Constructor

    1. If the programmer does not specify the constructor in the program then compiler provides the default constructor.
    2. In C++ we can overload the default compiler generated constructor
    3. In both cases (user created default constructor or default constructor generated by compiler), the default constructor is always parameterless.

    Syntax

    class_name() {
    -----
    -----
    }
    

    Example of Default Constructor

    Let us take the example of class Marks which contains the marks of two subjects Maths and Science.

    #include<iostream>
    using namespace std;
    class Marks
    {
    public:
       int maths;
       int science;
       //Default Constructor
       Marks() {
          maths=0;
          science=0;
       }
       display() {
          cout << "Maths :  " << maths <<endl;
          cout << "Science :" << science << endl;
       }
    };
    int main() {
      //invoke Default Constructor
      Marks m;
      m.display();
      return 0;
    }
    

    Output :

    Maths :  0
    Science : 0
    

    C++ Constructor Types #2 : Parametrized Constructor

    This type of constructor can take the parameters.

    Syntax

    class_name(Argument_List) {
    -----
    -----
    }
    

    Example of Parametrized Constructor

    Let us take the example of class ‘Marks’ which contains the marks of two subjects Maths and Science.

    #include<iostream>
    using namespace std;
    class Marks
    {
    public:
       int maths;
       int science;
       //Parametrized Constructor
       Marks(int mark1,int mark2) {
          maths = mark1;
          science = mark2;
       }
       display() {
          cout << "Maths :  " << maths <<endl;
          cout << "Science :" << science << endl;
       }
    };
    int main() {
      //invoke Parametrized Constructor
      Marks m(90,85);
      m.display();
      return 0;
    }
    

    Output

    Maths :  90
    Science : 85
    

    C++ Constructor Types #3 : Copy Constructor

    1. All member values of one object can be assigned to the other object using copy constructor.
    2. For copying the object values, both objects must belong to same class.

    Syntax

    class_Name (const class_Name &obj) {
       // body of constructor 
    }
    

    Example of Copy Constructor

    Let us take the example of class ‘Marks’ which contains the marks of two subjects Maths and Science.

    #include<iostream>
    using namespace std;
    class marks
    {
    public:
        int maths;
        int science;
        //Default Constructor
        marks(){
          maths=0;
          science=0;
        }
        //Copy Constructor
        marks(const marks &obj){
          maths=obj.maths;
          science=obj.science;
        }
        display(){
          cout<<"Maths :   " << maths
          cout<<"Science : " << science;
        }
    };
    int main(){
        marks m1;
        /*default constructor gets called 
             for initialization of m1  */      
        marks m2(const marks &m1);
        //invoke Copy Constructor
        m2.display();
        return 0;
    }
    

    Output

    Maths :  0
    Science : 0
    

    C++ Overloading assignment operator

    We already know the assignment operator in C++. In this tutorial we will be learning concept of C++ Overloading assignment operator.

    Assignment operator in C++

    1. Assignment Operator is Used to assign value to an variable.
    2. Assignment operator is denoted by equal to sign.
    3. Assignment operator have Two values L-Value and R-value. Operator copies R-Value into L-Value.
    4. It is a binary operator.

    C++ Overloading Assignment Operator

    1. C++ Overloading assignment operator can be done in object oriented programming.
    2. By overloading assignment operator, all values of one object (i.e instance variables) can be copied to another object.
    3. Assignment operator must be overloaded by a non-static member function only.
    4. If the overloading function for the assignment operator is not written in the class, the compiler generates the function to overload the assignment operator.

    Syntax

    Return_Type operator = (const Class_Name &)

    Way of overloading Assignment Operator

    #include<iostream>
    using namespace std;
    class Marks
    {
       private:
          int m1;            
          int m2;           
       public:
       //Default constructor
       Marks() {
            m1 = 0;
            m2 = 0;
       }
       // Parametrised constructor
        Marks(int i, int j) {
            m1 = i;
            m2 = j;
        }
       // Overloading of Assignment Operator
        void operator=(const Marks &M ) { 
            m1 = M.m1;
            m2 = M.m2;
        }
       void Display() {
          cout << "Marks in 1st Subject:" << m1;
          cout << "Marks in 2nd Subject:" << m2;
        }   
    };
    int main()
    {
      // Make two objects of class Marks
       Marks Mark1(45, 89);
       Marks Mark2(36, 59); 
       cout << " Marks of first student : "; 
       Mark1.Display();
       cout << " Marks of Second student :"; 
       Mark2.Display();
       // use assignment operator
       Mark1 = Mark2;
       cout << " Mark in 1st Subject :"; 
       Mark1.Display();
       return 0;
    }
    

    Explanation

     private:
          int m1;            
          int m2;  

    Here, in Class Marks contains private Data Members m1 and m2.

    Marks Mark1(45, 89);
    Marks Mark2(36, 59);

    In the main function, we have made two objects ‘Mark1’ and ‘Mark2’ of class ‘Marks’. We have initialized values of two objects using parametrised constructor.

    void operator=(const Marks &M; ) { 
    	m1 = M.m1;
    	m2 = M.m2;
    }
    

    As shown in above code, we overload the assignment operator, Therefore, ‘Mark1=Mark2’ from main function will copy content of object ‘Mark2’ into ‘Mark1’.

    Output

    Marks of first student : 
    Mark in 1st Subject : 45 
    Marks in 2nd Subject : 89
    Marks of Second student : 
    Mark in 1st Subject : 36 
    Marks in 2nd Subject : 59
    Marks of First student : 
    Mark in 1st Subject : 36 
    Marks in 2nd Subject : 59