Basic concepts of object oriented programming in C++

The blog covers the basic concepts of object oriented programming in c++  

In software construction, object-oriented programming is a way to construct software  although there are many types of programming languages are available such as

  • Structured programming language
  • Function oriented  programming language
  • Aspect-oriented programming language(AOP)
  • Object-oriented programming language(OOPS)

A well known and famous programming language is an object-oriented programming language that all the current programming supports oops

Concept of oops

Let us understand the concept of oops through function-oriented language such as C

Why?

 because C support C++

The people who know C++ are well aware of C so, I will use C to explain OOPS

Suppose if I am developing a software  for school management system then I will look at that system by a collection of function if I am using function-oriented language such as C

The user of the system will be utilizing this function to complete his tasks

So, you can develop software  in the form of a collection of functions if you are using function-oriented programming

The software “school management system” will be based on a collection of function

Rendered by QuickLaTeX.com

The above figure shows the  example of software development  in a function-oriented language

the software  called “school management system” contain four functions such as

student_name(); 

student_roll_no();

 student_fees();

and student_age();

For object-oriented programming language

such as C++ the complete software consists of a collection of objects

Where Each object will have its function and data

The user of the system will be utilizing these objects to complete his tasks

Object-oriented language is best suited for large size systems

Rendered by QuickLaTeX.com

The above figure a software called “school management system”

where it contain four departments which are nothing but objects and each object will have relevant function + data

Fundamentals of object-oriented programming language

  • Classes
  • Objects
  • reusability
  • Abstraction
  • Inheritance
  • Polymorphism

What is a class? And what is an object?

In simple terms think class as datatype [float] and object is a variable of that float data type

Class and Object

Rendered by QuickLaTeX.com

Here Bird is class and parrot and owl are the object

Rendered by QuickLaTeX.com

Here flower is a class and rose and lily are the object

The structure of a class contains

Two keywords

  • Public
  • Private

Public: means data and functions  can be accessed outside the class

Private: means data and functions are hidden that it cannot be accessed outside the class by other functions

Reusability

Once you have created a class and tested then it can be redistributed to the other members of your team to use it in their code

New instances of classes can be created from existing class instead of redeveloping the existing code

It will save time for the  other member of a team they won’t waste time in rediscovering the wheel instead they will focus on writing a new code

Abstraction

Think abstraction as a password or a key given to you to just login into your account without worrying about how the whole the systems works

Another example consider a laptop  and the abstract for  laptop is a keyboard pad  through which you control the laptop

 you should not  need to know how motherboards work with its transistors, capacitors, resistors, microcontroller so, in a way, it reduces the complexity for you

in C++ you use the headers file without knowing all its internal function for example you use “cout” in the program to print output on the screen

here “cout” is  abstract for you because you just know the “cout” and you don’t know all its internal functions that produce output on the screen

If you haven’t written any C++ program yet, then see this blog post for Writing the first C++ program

Const

Const(constant) is a keyword in C and it is also called literal, which tells the compiler that the value of the variable will not be changed throughout the program

Why we used it?

Usually, it is used to replace the #define constants with const and is written in uppercase letters as a reminder that they are constants

The advantage of const over #define constants  is that you can control the scope of the variable [local or global]

If we use a variable then we can change its value at any time we like throughout the program

#include <iostream>
using namespace std;
int main()
{
        int a=10;// here a is a variable name
         a=20;
         a=30;// here a is a variable name
    cout <<"a=" <<a<<endl;
    return 0;
}

Output

a=30

On the other hand, if we declare a variable(a) as a const type, then, in that case, any attempt to assign a new value to a const type will produce an error

#include <iostream>
using namespace std;
int main()
{
      const int a=10;// here a is a variable name
         a=20;//error:assignment of read-only variable 'a'
         a=30;
    cout <<"a=" <<a<<endl;
    return 0;
}

Initialization of const

const value must be initialized when it is created

Const int a=get_size(); //ok , initialized at compile time
Const int b=200; //ok, initialized at compile time
Const int c;       // error 'c' is uninitialized 
int i=10;
Const int j=i;//ok, the value of i is copied to j
int k=j;     //ok, the value of j is copied to k

Lets see a practical example of const by finding the surface area of a sphere

#include <iostream>
using namespace std;
int main()
{
    float r, a;
    const float pI=3.14159;
    cout<<"Enter the value of radius r:"<<endl;
    cin>>r;
    a=4*pI*r*r;
    cout<< endl<<"The surface area of a sphere = "<<a;
    return 0;
}

Output

Enter the value of radius r:
20
The surface area of a sphere = 5026.54

Reference variable

When a variable is declared as reference(& variable) then it will become an alternative name for the current variable

We can also say, it is a linked variable because a change in one variable makes the changes in another variable

Note: in C we say (&) as an address operator but in C++ we  refer to it as a reference variable

Where do we use it?

  • Copy constructor
  • Operator overloading

Initialization of reference variable

A reference variable must be initialized when it created

int a=8;
int&b; //error
b=a;

Example:

Float account_number=255; // here account_number is a variable name
Float &ac_num= account_number; // here ac_num is a reference name

If we create the variable ac_num as a reference to the variable account_number then account_number and ac_num can be used interchangeably to represent the same variable

Both account_number and ac_num will refer to the same variable

#include <iostream>
using namespace std;
int main()
{
    int a=10;// here a is a variable name
    int &b=a;//b is a reference name to a variable a
    int &c=b;//c is a reference name to a variable b
    cout <<"a=" <<a<<endl;
    cout <<"b=" <<b<<endl;
    cout <<"c=" <<c<<endl;
    c=900;//Change in one variable makes the change in the remaining variables which is associated with it
    cout <<"a=" <<a<<endl;
    cout <<"b=" <<b<<endl;
    cout <<"c=" <<c<<endl;
    return 0;
}

Output

a=10
b=10
c=10
a=900
b=900
c=900

In C we can pass the parameters to the functions in two ways

  • Call by value
  • Call by address

In C++ we can pass the parameters to the functions by an additionally  introduced concept called call by reference

The problem:

In C when we make a function call by address we need to declare formal parameters as pointers

  • Pointers are not secure
  • Reference variables are secured when compared with pointer variables
  • Referencing offers a clean elegant and efficient way to pass parameters to functions

Finally, instead of passing parameters to functions by call by value or call by address, we can use call by reference

Call by value

#include <iostream>
using namespace std;
void swap_value(int a ,int b );
int main()
{
    int a=100,b=200;
    swap_value(a,b);// call by value
    return 0;
}
void swap_value(int a,int b)
{
    int temp;
    temp= a;
    a=b;
    b=temp;
    cout <<"call by value" <<endl;
     cout <<"a=" <<a<<endl;
    cout <<"b=" <<b<<endl;
}

Output

call by value
a=200
b=100

Call by address

#include <iostream>
using namespace std;
void swap_address(int *a,int*b);
int main()
{
    int a=100,b=200;
      swap_address(&a,&b);// call by address
    cout <<"a=" <<a<<endl;
    cout <<"b=" <<b<<endl;
    return 0;
}
void swap_address(int *a,int*b)
{
    int temp;
    temp= *a;
    *a=*b;
    *b=temp;
    cout <<"call by address" <<endl;
}

Output

call by address
a=200
b=100

Call by reference

#include <iostream>
using namespace std;
void swap_reference(int &a,int &b);
int main()
{
    int a=100,b=200;
    swap_reference(a,b);// call by reference
    cout <<"a=" <<a<<endl;
    cout <<"b=" <<b<<endl;
    return 0;
}
void swap_reference(int &a,int &b)
{
    int temp;
    temp= a;
    a=b;
    b=temp;
    cout <<"call by reference" <<endl;
}

Output

call by reference
a=200
b=100

Bool data type

The bool data type can take two values that is true(1) and false(0) which is commonly used for comparisons

In C  we don’t have a Boolean data type but we can use integers for Boolean testing ( _Bool is an unsigned integer for which we can assign 0 or 1)

#include <stdio.h>
//#include<stdbool.h>
int main()
{
    _Bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
printf("%d\n%d",x,y);
//printf("value =%d,value=%d",true,false);// error if you didn’t include<stdbool.h>
    return 0;
}

Output

1
0

In C Instead of using  _Bool we can use bool by including a file called #include<stdbool.h>  which also defines constants true as 1 and false as 0

#include <stdio.h>
#include<stdbool.h>
int main()
{
 bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
printf("%d\n%d",x,y);
printf("\nvalue=%d,value=%d",true,false);// error if you didn’t include<stdbool.h>
    return 0;
}

Output

1
0
value =1, value=0

In C++ we don’t need any header file to include

#include <iostream>
using namespace std;
int main()
{
    bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
cout<<endl<<x<<endl<<y;
cout<<endl<<"value="<<true<<endl<<"value="<<false;
    return 0;
}

Output

1
0
value=1
value=0

Some arithmetic with a bool

#include <iostream>
using namespace std;
int main()
{
bool a=10,b=20,c=30;
int x=a+b;
bool y=a+b;
int z=b*c;
cout<<endl<<x<<endl<<y<<endl<<z;
    return 0;
}

Output

2
1
1

Comments

In  C and C++ we can use two ways to comment out a code

First way: use /* */ style to comment out a block of code

Second way: use // style to comment out a single line of code

Commenting means anything which is lying between /* */ will be ignored similarly, by using  // we can comment out the whole line of code

Strong type checking

In C we can call the function strlwr() without file #include<string.h> but with a warning such as “implicit declaration of function ‘strlwr’

#include <stdio.h>
//#include<string.h>
int main()
{
    char str[]="HI, THERE";
    strlwr(str);//convert a string to lowercase letter
    printf("%s",str);
    return 0;
}

Output

Hi, there

In C++ no function can be called unless its prototype is available to the compiler to crosscheck the return type and the parameters of a function which is known as strong type checking

C++ throws an error for a function call strlwr(), if we didn’t include the file #include<string.h>

#include <iostream>
//#include<string.h>
using namespace std;
int main()
{
    char str[]="HI, THERE";
    strlwr(str);//convert a string to lowercase letter
    cout << str<< endl;
    return 0;
}

Anonymous unions

Anonymous unions are the unions that do not have any union< tag> or union name but we can access its elements directly without using a union variable  

In C we can not access union elements without a union variable  

#include <stdio.h>
int main()
{
    union abc{
int a;
char b;
};
    a=50; //error a is undeclared and b is undeclared
    printf("a=%d\n", a);
    printf("b=%c\n", b);
    return 0;
}

In C++ we can access union elements without a union variable and union <tag>or union name

Similarly, if you use the keyword struct instead of the keyword union then, in that case, you will see an error[abstract declaratory ‘main()::<anonymous struct>’ used as declaration]

#include <iostream>
using namespace std;
int main()
{
    union {
int a;
char b;
};
    a=50;
    cout << "a=" <<a<< endl;
    cout << "b=" <<b<< endl;
    return 0;
}

Output

a=50
b=2

In C++ if we declare the anonymous union outside the main() function then we can not access its elements without a variable name

#include <iostream>
using namespace std;
   union {
int a;
char b;
};
int main()
{
    a=50; //error: a was not declared in this scope
    cout << "a=" <<a<< endl;
    cout << "b=" <<b<< endl;//Error: b was not declared in this scope
    return 0;
}

Anonymous enums

The anonymous enums concept is similar to the anonymous union

#include <iostream>
using namespace std;
int main()
{
    enum {mon,tue,wed,thus,fri,sat,sun};
    cout << "day=" <<sat<< endl;
    return 0;
}

Output

day=5

Function with default arguments

Let’s see a C example to understand the function with default arguments concept

 the below program makes four function calls but only one call will execute

why?

Because in C we have a rule: that the function definition should match with function prototype

So, to solve this problem in C++ they introduced the concept called functions with default arguments

#include <stdio.h>
#include <stdlib.h>
int calsum(int a, int b, int c);
int main()
{
    int sum,sum1,sum2,sum3;
    sum=calsum(10,20,30);//result: 60
    sum1=calsum(30,30);// Error arguments do not match
    sum2=calsum(30);// Error arguments do not match
    sum3=calsum();// Error arguments do not match
    printf("sum=%d\n",sum);
    printf("sum1=%d\n",sum1);
    printf("sum2=%d\n",sum2);
    printf("sum3=%d\n",sum3);
    return 0;
}
int calsum(int a, int b, int c)
{
    int d;
    d=a+b+c;
    return (d);
}

C++ allows you to call a function without passing its arguments

#include <iostream>
using namespace std;
int calsum(int a=1, int b=2, int c=3);// arguments are initialized
int main()
{
    cout << "sum="<<calsum(10,20,30)<< endl;//result: 60=10+20+30 //3 arguments
     cout <<"sum="<<calsum(30,30)<< endl;//result: 63=30+30+3 //2 arguments
    cout << "sum="<<calsum(30)<< endl;//result: 35=30+2+3 //1 arguments
    cout << "sum="<<calsum()<< endl;//result: 6=1+2+3 //0 arguments
    return 0;
}
int calsum(int a, int b, int c)
{
    int d;
    d=a+b+c;
    return (d);
}

Output

sum=60
sum=63
sum=35
sum=6

Function definition outside the class

#include <iostream>
using namespace std;
class rectangle
{
private:
    int length, breath;
public:
    void getdata()//Member function of a class rectangle
   {
        cout<<endl<<"enter length and breath";
        cin>>length>> breath;
    }
    void setdata(int l, int b)//Member function of a class rectangle
    {
        length=l;
         breath=b;
    }
void displaydata()////Member function of a class rectangle
{
    cout<<endl<<"length="<<length;
    cout<<endl<<"breath="<< breath;
}
};//Class is terminated by a semicolon
int main()
{
   rectangle r1,r2; // r1, r2 are the objects of a class rectangle
   r1.getdata();// use the dot operator to access the class member function
   r1.displaydata();
   r2.setdata(5,8);
   r2.displaydata();
}

Output

Enter length and breath 2 6
Length=2
Length=6
Length=5
Length=8

The concept of structure, union, and enum in C and C++

  • In C we can have only data types and variables as the elements of a structure, union, and enum but in C++ we can have  data types, variables, and functions as the elements of a structure, union, and enum
  • To declare a variable of structure, union, and enum we need struct, union, and enum keywords but in C++ we don’t need them (you can declare it as we declare an object of a class)
  • In C  the elements of a structure, union, and enum  are public but in C++  the elements of a structure, union, and enum can be[ public, private, protected ]

A C example for structure, union, and enum

#include <stdio.h>
#include <stdlib.h>
void display(int x, int y);// function prototype declaration
struct demo //defining a structure
{
    int x;
    int y;
};
union demo_u //defining a union
{
    int a;
    int b;
};
enum status{married,unmarried,divorced};// enum declaration
 void display(int x, int y)//function definition
    {
        printf("\n%d\n%d",x,y);
    }
int main()
{
   struct demo d={10,20};//Declaring a structure variable d and initializing
   union demo_u u={30};//Declaring a union variable u and initializing
   enum status s;//Declaring an enum variable s and
   s=divorced;
   printf("status=%d",s);
   display( d.x,d.y);
   display( u.a,u.b);
    return 0;
}

Output

status=2
10
20
30
30

A C++ example for structure, union, and enum

#include <iostream>
using namespace std;
void display(int x, int y);// function prototype declaration
void display(int a, int b);// function prototype declaration
struct demo //defining a structure
{
    int x;
    int y;
     void display(int x, int y)//function definition
    {
        cout<<"\n"<<x<<"\n"<<y<<endl;
    }
};
union demo_u //defining a union
{
    int a;
    int b;
     void display(int a, int b)//function definition
    {
        cout<<a<<"\n"<<b<<endl;
    }
};
enum status{married,unmarried,divorced};// enum declaration
int main()
{
    demo d={10,20}; //Declaring a structure variable d and initializing
    demo_u u={30}; //Declaring a union variable u and initializing
   status s=divorced; //Declaring an enum variable s and initializing
  cout<<endl<<"status="<<s;
   d.display( d.x,d.y);
   u.display( u.a,u.b);
    return 0;
}

Output

status=2
10
20
30
30

Using the private keyword in a C++ structure

#include <iostream>
using namespace std;
struct demo
{
    private:
    int x;//Data member
    int y;//Data member
    void display()// FUNCTION
    {
        cout<<x<<" \n"<<y<<endl;
    }
};
int main()
{
     demo d;
   d.x=10;
   d.y=50;
   d.display(); //Error  as x and y are private
    return 0;
}

Difference between a class and structure

  • Class data members are private while the structure data members are public
  • A class can be inherited but structures won’t
  • Class is used to create big and complex programs while structures are used to create
#include <iostream>
using namespace std;
struct demo
{
    int x;//Data member
    int y;//Data member
    void display()// FUNCTION
    {
        cout<<x<<" \n"<<y<<endl;
    }
};
int main()
{
     demo d;
   d.x=10;
   d.y=50;
   d.display(); //Error  as x and y are private
    return 0;
}

Output

10
50

Class data members are private small programs

#include <iostream>
using namespace std;
class demo
{
    int x;
    int y;
    void display()// FUNCTION
    {
        cout<<x<<" \n"<<y<<endl;
    }
};
int main()
{
     demo d;
   d.x=10;
   d.y=50;
   d.display(); //Error  as x and y are private
    return 0;
}

Basic class program

#include <iostream>
using namespace std;
class rectangle
{
private:
    int length, breath;
public:
    void getdata();//Function prototype declaration
    void setdata(int l, int b);//Function prototype declaration
    void displaydata();//Function prototype declaration
};//Class is terminated by a semicolon
    void rectangle::getdata()//Function definition
   {
        cout<<endl<<"enter length and breath";
        cin>>length>> breath;
    }
    void rectangle::setdata(int l, int b)//Function definition
    {
        length=l;
         breath=b;
    }
void rectangle::displaydata()//Function definition
{
    cout<<endl<<"length="<<length;
    cout<<endl<<"breath="<< breath;
}
int main()
{
   rectangle r1,r2; // r1, r2 are the objects of a class rectangle
   r1.getdata();// use the dot operator to access the class member function
   r1.displaydata();
   r2.setdata(5,8);
   r2.displaydata();
}

Output

Enter length and breath 2 6
Length=2
Length=6
Length=5
Length=8

Constructor

Constructors are the member functions of a class

There are three types of constructors

  • Default constructor
  • Parametrized constructor
  • Copy constructor

Why constructors?

  • They are used to assign value to the data members of a class(when an obj is created a constructor will be invoked automatically)
  • Data members can’t be directly initialized in the class
  • The initialization of data members can be done only through constructors

Note: if we don’t write a constructor in the class then at that instant, the compiler will provide a default constructor

Rules for creating a constructor

  1. A constructor should have the same name as the class name
  2. No return type is used for constructors
  3. A constructor or a destructor has to be declared in public

Automatic initialization of an object

When the object t of the class test is created then  at that instant, the constructor test() is executed automatically and the  value of ‘a’ becomes 20 that is called automatic initialization of an object

#include <iostream>
using namespace std;
class test
{
private:
    int a;
public:
    test()//default constructor 
    {
        a=20;// data item
    }
 void displaydata()//Function definition
   {
        cout<<endl<<"value of a="<<a;
    }
};
int main()
{
   test t;//obj t of class test
   t.displaydata();
   return 0;
}

Output

Value of a=20
#include <iostream>
using namespace std;
class integer
{
private:
    int i;
public:
    void getdata()
    {
        cout<<endl<<"enter any integer value";
        cin>>i;
    }
    void setdata(int j)//Function definition
    {
        i=j;
    }
integer()//Zero argument constructor or default constructor
{
}
integer(int j)//One argument constructor or parameterized constructor
{
   i=j;
}
 void displaydata()//Function definition
   {
        cout<<endl<<"value of i="<<i;
    }
};
int main()
{
   integer i1(900), i2, i3;
   i1.displaydata();
   i2.setdata(500);
   i2.displaydata();
   i3.getdata();
   i3.displaydata();
}

Output

value of i=900
value of i=500
enter any integer 8
value of i=8

Constructor  outside the class

#include <iostream>
using namespace std;
class integer
{
private:
    int i;
public:
    integer();//constructor declaration
    integer(int j);//constructor declaration
    void getdata()
    {
        cout<<endl<<"enter any integer value";
        cin>>i;
    }
    void setdata(int j)//Function definition
    {
        i=j;
    }
 void displaydata()//Function definition
   {
        cout<<endl<<"value of i="<<i;
    }
};
integer::integer()//Zero argument constructor or default constructor
{
}
integer::integer(int j)//One argument constructor or parameterized constructor
{
   i=j;
}
int main()
{
   integer i1(900), i2, i3;
   i1.displaydata();
   i2.setdata(500);
   i2.displaydata();
   i3.getdata();
   i3.displaydata();
}

Output

value of i=900
value of i=500
enter any integer 8
value of i=8

Copy constructor

A copy constructor is a constructor  that is used to initialize the current obj values with another obj values

Copy constructor will have(class_type_parameter and & reference parameter) and it will receive another obj to initialize the current obj

Where it is used?

We use it for operating overloading

#include <iostream>
using namespace std;
class sample
{
    private:
    int a, b;
    public:
        sample(int a, int b)// Parametrized constructor
        {
            this->a=a;
            this->b=b;
        }
         sample(sample&old_obj)// Copy constructor(sample(sample(class_name)&(reference variable)old_obj(reference obj))
        {
            a=old_obj.a; //old_obj data is copied to new obj
            b=old_obj.b;
        }
        void display()
        {
            cout<<"a="<<a<<endl;
            cout<<"b="<<b<<endl;
        }
};
int main()
{
// values of data items will become a=100 and b=200
    sample s1(100,200);//Calling Parametrized constructor
//now we want to copy s1 values to s2
    sample s2(s1); //Calling Copy constructor
    s1.display();
    s2.display();
    return 0;
}

Output

a=100
b=200
a=100
b=200

Operator overloading

Let us understand the concept of operator overloading with the help of  function overloading

Function overloading means we can have multiple functions with the same name but operator overloading is a little bit different

Operator overloading means we can use an operator symbol instead of a function name to do a particular task

Generally, operators are designed to do a particular operation on an operand

The unary operator can act on a single operand like +,-,++,–,!

Ex: +4(one operand)

The binary operator can act on two operands like +,-,! ,*

Ex: 8+4(two operand)

The problem with operators

All the operators are designed to work with predefined data types such as(int, float, char, and double)

With the help of the + operator, you can add two integers

Int a=8, int b=9 ,total;

Total= a+b;

But the problem is that we can’t add objects like how we added the integers because objects are instances of a class and a class is a user-defined data type

Obj1+obj2    ——->ERROR

So, to avoid this problem, C++ has introduced the concept of operator overloading and with the help of operator overloading we can add two objects of user-defined data type

We can overload all the C++ operators except some operators such as

:: scope resolution operator

.  , .*dot , dot star(means member access operator of a class)

Conditional operator(?:)

Sizeof()

The syntax for function definition

Return_type function_name(argument_list)
{
}

The syntax for operator overloading

Return_type operator_symbol(argument_list)
{
}

Here in the above syntax operator is a keyword and the symbol is an operator symbol

Note: if you have observed you might notice in place of the function name we exchanged it with the operator symbol(where the operator is a keyword and the symbol is an operator symbol)

Let us see a simple example to understand  == operator  overloading with the help of a function

First, In place of the operator keyword, we will use a function called compare (test t2)  so, to compare the value we need two values one is implicit(inside obj)[test class], and the other one is explicit(outside obj)[t2 object]

#include <iostream>
using namespace std;
class test
{
    private:
    int a; // data item
    public:
        void getdata() //Member function to get a value
        {
            cin>>a;
        }
        void compare(test t2)//To compare the two  values we need two arguments one is implicit (i.e( test) class name) and another one is explicit (i.e t2 obj)
        {
            if(a==t2.a)
                cout<<"object are equal";
            else
                cout<<"object are not equal";
        }
};
int main()
{
    test t1, t2;
    cout << "enter t1 object a value" << endl;
    t1.getdata();
    cout << "enter t2 object a value" << endl;
    t2.getdata();
    t1.compare(t2);
    return 0;
}

Output

enter t1 object a value
 5
enter t2 object a value
 5
object are equal

 overloading == operator

Second, to overload the == operator we need to replace the compare function name with the operator symbol ==

Rule: to overload the operator the left side value should be the object of the same class  

For example, consider the below expression from below program

t1==t2

here,t1 is a left-side value(object of the same class test) and == is an equality operator

#include <iostream>
using namespace std;
class test
{
    private:
    int a; // data item
    public:
        void getdata() //Member function to get a value
        {
            cin>>a;
        }
        void operator ==(test t2)//To compare the two  values we need two arguments one is implicit (i.e( test) class name) and another one is explicit (i.e t2 obj)
        {
            if(a==t2.a)
                cout<<"object are equal";
            else
                cout<<"object are not equal";
        }
};
int main()
{
    test t1, t2;
    cout << "enter t1 object a value" << endl;
    t1.getdata();
    cout << "enter t2 object a value" << endl;
    t2.getdata();
    t1==t2;
    return 0;
}

Output

enter t1 object a value
 5
enter t2 object a value
 5
object are equal

Overloading the unary operators

As we know, a unary operator will act on a single operand whereas the binary operator will act on operands

When the binary operator is overloaded it requires two objects one is implicit(inside) and the other is explicit(outside) but for unary operator overloading we require only an implicit(inside) object

#include <iostream>
using namespace std;
class demo
{
private:
    int a;
public:
    demo()//default constructor
    {
        a=0;// data item
    }
    void operator ++()//Increment operator overloading
    {
        ++a;
    }
     void operator --()//Decrement operator overloading 
    {
        --a;
    }
    void showdata()//function
    {
        cout<<"a="<<a<<endl;;
    }
};
int main()
{
    //obj d is created so, that it will automatically be initialized with 0 because the constructor says so
    demo d;
    ++d;
    d.showdata();
    --d;
    d.showdata();
}

Output

a=1
a=0

This pointer

This pointer is a keyword that refer current instant of a class

Why we use it?

To reduce ambiguity in case, if you have two variables with same name

#include <iostream>
using namespace std;
class student
{
private:
     int s_id;
    string s_name;
public:
    //one way to set data           //another way to set data
    student(int s_id,string s_name) //student(int id,string name)
    {                           //{
      this->s_id=s_id;                // s_id=id;
      this->s_name=s_name;            // s_name=name;
    }                           // }
     void display( )
    {

        cout<<s_id<<""<<s_name<<endl;;

    }
};
int main()
{
    student s1=student(12,"mohammed");
    student s2=student(17,"anees");
    s1.display();
    s2.display();
    return 0;
}

Output

12 mohammed
17 anees

Resource

  • Let us C++ by Yashavant Kanetkar
  • Let us C by Yashavant Kanetkar
  • Data structures using C by Reema Thareja

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.