Explain Objects and Classes in C++.

 Explain Objects and Classes in C++


1] Explain basic concept of class.

  • A class is a template that specifies the attributes and behavior of things or objects.
  • A class is a blueprint or prototype from which objects are created .
  • A class is the implementation of an abstract data type (ADT).
  • It defines attributes and methods.
👉Object declaration:
  • In following example class employee is created and 'a' is object of this class.
          class item
          {
               // data members and member functions 
         }a;
  • In above syntax class name is item, and a is object of that class.
  • Object declaration can be also done in main() function as follows:
          int main()
          {
                item a;
          }
👉Accessing class member:
  • Private members of the class can only accessed by the members with in that class.
  • Public members of the class can be accessed outside the class also.
  • For accessing class member outside class can be done by using dot operator and object of that class using following syntax,
           object-name . function-name(actual-arguments);
  • Member functions of the class can be declared outside class definition also as follows,
👉Syntax:
               class item
               {
               public:
                         void getdata ();
               };
               void item::getdata();

👉Example:
               #include<iostream>
               using namespace std;
            
               class employee                                //class
               {
                              char name[10];               //data member
                              int id;                               //data member
                         public:
                              void getdata();                 //prototype declaration
                              void putdata();                 //prototype declaration
               };
               void employee::getdata()                //member function
               {
                         cout<<"Enter name and id of employee: ";
                         cin>>name<<id;
               }
               void employee::putdata()                //member function
               {
                         cout<<"Display name and id of employee: ";
                         cout<<name<<id;
               }
               int main()
               {
                         employee x;
                         x.getdata();
                         x.putdata();
               }

2] Explain memory allocation of objects with example.
  • The member functions are created and placed in the memory space only once when they are defined as part of a class specification.
  • No separate space is allocated for member functions when the objects are created .
  • Only space for member variable is allocated separately for each object.
  • A separate memory location for the objects happens, because the member variables will hold different data values for different objects.
👉Example:
               class item
               {
                         public:
                         int id, cost;
                         void getdata ():
               };
               int main()
               {
                         item x,y,z;
               }
  • In above example each object x, y and z has separate space for both id and cost.
  • Means value of id and cost can be different for each object.
  • But no default space is allocated to function when object is declared.
  • Required separate space is allocated to function during calling of that function.
3] Explain Public and Private access modifier (specifier) for C++ 
    classes.
👉Public:
  • Public members of the class are accessible by any program from anywhere.
  • There are no restrictions for accessing public members of a class.
  • Class members that allow manipulating or accessing the class data are made pub;ic.
👉Private:
  • Private members of the class can be accessed within the class and from member functions of the class.
  • They cannot be accessed outside the class or from other programs, not even from inherited class.
  • Encapsulation is possible due to the private access modifier.
  • If one tries to access the private members outside the class then it results in a compile time error.
  • If any other access modifier is not specified then member default acts as Private member.
Example:
               #include<iostream>
               using namespace std;

               class ABC
               {
                         public:
                              int a;
                         private:
                              int b;
               };
               int main()
               {
                         ABC x;
                         x.a=5;
                         cout<<"Value of public variable = "<<x.a;
               }
               Output
               5
  • In above program b is private member of class ABC.
  • So we cannot use it with objects of ABC outside the class, Means we cannot use x.b in main as x.a shown above.
4] Explain Static data members and static member functions
     with example.
👉Static data members:
  • Data members of the class which are shared by all objects are known as static data members.
  • Only one copy of a static variable is maintained by the class and it is common for all objects.
  • Static members are declared inside the class and defined outside the class.
  • It is initialized to zero when the first object of its class is created. No other initialization is permitted.
  • It is visible only within the class but its lifetime is the entire program.
  • Static members are generally used to maintain values common to the entire class.
👉Static member functions:
  • Static member functions are associated with a class, not with any object.
  • They can be invoked using class name, not object.
  • They can access only static members of the class.
  • They cannot be virtual.
  • They cannot be declared as constant or volatile.
  • A static member function can be called, even when a class is not instantiated.
  • There cannot be static and non-static version of the same function.
  • A static member function does not have this pointer.
Example:
               #include<iostream>
               using namespace std;
               class item
               {
                         int number;
                         static int count;           //static variable declaration
                         public:
                                   void getdata (int a)
                                   {
                                             number = a;
                                             count++;
                                   }
                                  static void getcount() //the only difference from
                                                                        above program
                                   {
                                              cout<<"value of count: "<<count;
                                   }
               };
               int item :: count;                   //static variable definition
               int main()
               {
                         item a,b,c;
                         a.getdata(100);
                         b.getdata(200);
                         c.getdata(300);
                         a.getcount();
                         b.getcount();
                         c.getcount();
                         getch();
                         return 0;
               }
               Output:
               value of count : 3
               value of count : 3
               value of count : 3

5] What is constructor? List out characteristics of constructors.
  • A constructor is a "special" member function which initializes the objects of class.
👉 Properties of constructor:
  • Constructor is invoked automatically whenever an object of class is created.
  • Constructor name must be same as class name.
  • Constructor should be declared in the public section because private constructor cannot be invoked outside the class so they are useless.
  • Constructors do not have return types and they cannot return values , not even void.
  • Constructors cannot be inherited, even though a derived class can call the base class constructor.
  • Constructors cannot be virtual.
  • An object with a constructor cannot be used as a member of a union.
  • They make implicit calls to the operators new and delete when memory allocation is required.
6] Explain types of constructor with example.
  •   There are mainly  three types of constructor as follows:
1. Default constructor:
  • Default constructor is the one which invokes by default when objects of the class is created.
  • It is generally used to initialize the value of the data members.
  • It is also called no argument constructor.
👉Example:
               class integer
               {
                         int m,n;
                         public:
                         integer()      //Default constructor
                         {
                                   m=n=0;
                         }
               };
2. Parameterized constructor:
  • Constructor that can take arguments are called parameterized constructor.
  • Sometimes it is necessary to initialize the various data elements of different objects with different values when they are created.
  • We can achieve this objective by passing arguments to the constructor function when the objects are created.
👉Example:
               class integer
               {
                         int m,n;
                         public:
                         integer(int x, int y)      //Parameterized constructor
                         {
                                   m = x;
                                   n = y;
                         }
               };
3. Copy constructor:
  •  copy constructor is used to declare and initialize an object from another object.
  • For example, integer(integer &i); OR integer I2(I1);
  • Constructor which accepts a reference to its own class as a parameter is called copy constructor.
👉Example:
               class integer 
               {
                         int m, n;
                         public:
                         integer (rectangle &x)     // Copy constructor
                         {
                                   m = x.m;
                                   n = x.n;
                         }
               };

Constructor example:
               #include<iostream>
               using namespace std;
  
               class rectangle
               {
                         int length, width;
                         public:
                         rectangle()     // Default constructor
                         {
                                   length = 0;
                                   width = 0;
                         }
                         rectangle(int_length, int_width)  //Parameterized 
                                                                                  construcor
                         {
                                   length = _length;
                                   width = _width;
                         }
                         rectangle (rectangle &_r)  // Copy constructor
                         {
                                   length = _r.length
                                   width = _r.width
                         }
                         .........................
                         // other function for reading, writing and 
                         processing can be written here
                         .........................
               };
               int main ()
               {
                         rectangle r1;              // Invokes default constructor
                         rectangle r2(10,10);  // Invokes parameterized 
                                                               constructor
                         rectangle r3(r2);       // Invokes copy constructor
               }

7] Explain destructor with example.
  • Destructor is used to destroy the objects that have been created by a constructor.
  • Destructor is a member function whose name must be same as class name but is preceded by a tlide (~).
  • Destructor never takes any argument nor it returns any value nor it has return type.
  • Destructor is invoked automatically by the complier upon exit from the program. 
  • Destructor should be declared in the public section
👉Example:
               #include<iostream.h>
               using namespace std;

               class rectangle
               {
                         int length, width;
                         public:
                         rectangle ()     //constructor
                         {
                                   length = 0;
                                   width = 0;
                         }
                         ~rectangle ()     // Destructor
                         {
                         }
                         // other functions for reading, writing and processing                              can be written here
               };
               int main ()
               {
                         rectangle x;  //default constructor is called for this 
                                                objects
               }


8] Explain use of objects as function arguments with example.
  • Like any other data type function may be used as a function argument . It can be done in following two ways.
  1. A copy of the entire object is passed to the function.
  • This method is call pass by value.
  • Since copy of the object is passed to the function, any changes made to the object inside the function do not affect the object inside the function do not affect the object used to call the function.
  2. Only the address of the object is transferred to the function.
  • This method is called pass-by-reference.
  • When an address of the object is passed, the called function works directly on the actual object used in the call.
  • This means that any changes made to the object inside the function will reflect in the actual object.
  • This method is more efficient because it requires passing only addresses of the object, not an entire object.
👉Example:
               #include<iostream>
               using namespace std;
               class time
               {
                         int hours;
                         int minutes;
                         public:
                                  void gettime ( int h, int m)
                                   {
                                             hours=h;
                                             minutes=m;
                                   }
                                   void puttime(void)
                                   {
                                             cout<<hours<<"hours and";
                                             cout<<minutes<<"minutes<<"\n;
                                   }
                                   void sum(time, time); //declaration with objects
                                                                         as arguments
               };
               void time::sum(time t1, time t2)     // t1,t2 are objects
               {
                         minute = t1.minutes + t2.minutes;
                         hours = minutes/60;
                         minutes = minutes % 60;
                         hours = hours + t1.hours + t2.hours;
               }
               int main()
               {
                         time t1, t2, t3;
                         t1.gettime(2,45);                      // get t1
                         t2.gettime((3,30);                     // get t2
                         t3.sum(t1,t2);                           // t3 =t1 + t2
                         cout<<"t1 = "; t1.puttime();   // display t1
                         cout<<"t2 = "; t2.puttime();   // display t2
                         cout<<"t3 = "; t3.puttime();   // display t3

                         return 0;
               }

9] Explain operator overloading with example.
  • Operator overloading is compile time polymorphism.
  • The operator overloading provides mechanism to perform operations on user defined data type.
  • We can give special meaning to any operators in which program it is implemented .
  • Rules for operator overloading
          1. Only existing operator can be overloaded .
          2. The overloaded operator must have at least one operand 
              that is user defined type.
          3. We cannot change the basic meaning and syntax of an 
              operator.
          4. We cannot use friend function to overload certain operators.
          5. Unary operators, overloaded by means of a member 
              function, take no explicit arguments and return no explicit
              value,
               * But, those overloaded by means of a friend function , take
                  one reference argument.
          6. Binary operators overloaded through a member function 
              take one explicit argument and those which are overloaded
              through a friend function take two explicit arguments.
          7. When using binary operators overloaded through a member 
              function, the left hand operand must be an object of the 
             relevant class.
          8. We cannot overload following operators.
👉 Example for Unary Operator Overloading:
               #include<iostream>
               using namespace std;
               class sample
               {
                         int a,b;
                         public:
                         void getdata()
                         {
                                   a=10;
                                   b=20;
                         }
                         void operator -()     // Unary Member Function
                         {
                                   a = a - 5;
                                   b = b - 5;
                         }
                         void disp()
                         {
                                   cout<<"\nThe value of a="<<a;
                                   cout<<"\nThe value of b="<<b;
                         }
               };
               int main()
               {
                         sample S;
                         S.getdata();
                         -S;                    // Call Unary Member Function
                         S.disp();
                         getch();
                         return 0;
               }
               
               Output:
               The value of a=5
               The value of b=15

👉Example for Unary Operator Overloading using Friend         
     Function:
               #include <iostream>
               using namespace std;
               class sample
               {
                         int a,b;
                         public:
                         void getdata()
                         {
                                   a=10;
                                   b=20;
                         }
                         friend sample operator +(sample A)  // Unary Friend
                                                                                         Function
                        {
                                   A.a = A.a + 5;
                                   A.b = A.b + 5;
                                   return A;
                         }
                         void disp()
                         {
                                   cout<<"\nThe value of a="<<a;
                                   cout<<"\nThe value of b="<<b;
                         }
               };
               int main()
              {
                         sample S;
                         S.getdata();
                         S=+S;            // Call Unary Friend Function
                         S.disp();
                         return 0;
               }

               Output:
               The value of a=15
               The value of b=25

👉Example for Binary Operator Overloading 
               #include<iostream>
               using namespace std;
               class complex
               {
                         float real, imag;
                         public:
                         complex(float _real, float _imag)    // Constructor
                         {
                                   real = _real;
                                   imag = _imag;
                         }
                         void disp()
                         {
                                   cout<<"The value of real="<<real;
                                   cout<<"The value of imag ="<<imag;
                         }
                         void operator +(complex c)     //Binary Member
                                                                             Function
                         {
                                   real = real + c.real;
                                   imag = imag + c.imag;
                         }
               };
               int main()
               {
                         complex x(4,4);
                         complex y(6,6);
                         x + y;     // Call Binary Function
                         x.disp();
                              getch();
                              return 0;
               }

               Output:
               The value of real=10
               The value of imag=10

👉Example for Binary Operator Overloading using Friend 
     Function:
               #include<iostream>
               using namespace std;
               class complex
               {
                         float real, imag;
                         public:
                        complex(float _real, float _imag)  // Constructor
                        { 
                                  real = _real;
                                  imag = _imag;
                         }
                         void disp()
                         {
                                   cout<<"The value of real="<<real;
                                   cout<<"The value of imag="<<imag;
                         }
                         friend complex operator +(complex c, complex d)
                                                             // Binary Friend Function
                        {
                                  d.real = d.real + c.real;
                                  d.imag = d.imag + c.imag;
                                  return d;
                         }
               };
               int main()
               {
                         complex x(4,4);
                         complex y(6,6);
                         complex z = x + y;     // Call Binary Friend Function
                         z.disp();
               }
               Output:
               The value of real=10
               The value of imag=10

9] List out various type conversion techniques? Explain basic to class type conversion with example.
  • C++ provides mechanism to perform automatic type conversion if all variable are of basic type.
  • For user defined data type programmer have to convert it by using constructor or by using casting operator.
  • There type of situation arise in user defined data type conversion.
     1. Basic type to Class type
     2. Class type to Basic type
     3. Class type to Class type
  • Now we will see each situation with example
1. Basic type to Class type:
  • The basic type to class type conversion is done by using constructor.
👉Example:
               #include <iostream>
               using namespace std;
               class sample
               {
                         float a;
                         public:
                         sample(){}
                         sample(int x)  //Constructor to convert Basic to class 
                                                   type
                         {
                                   a=x;
                         }
                         void disp()
                         {
                                   cout<<"The value of a="<<a;
                         }
               };
               int main()
               {
                         int a=10;
                         sample S;
                         S=a;          // Basic to class type conversion
                         S.disp();
                         return 0;
               }
               Output:
               The value of a=10

11] Explain type conversion for class to basic type with example.
  • The class type to basic type conversion is done by using casing Operator.
  • The casting operator function should satisfy the following conditions.
          1. It must be a class member.
          2. It must not specify a return type.
          3. It must not have any arguments.
👉Example:
              #include<iostream>
               using namespace std;
               class sample
               {
                         float a;
                         public:
                         sample()
                         {
                                   a=10.23;
                         }
                         operator int();
               };
               sample:: operator int()  //Casting operator function
               {
                         int x;
                         x=a;
                         return x;
               }
               int main()
               {
                         sample S;
                         int y= S;          // Class to Basic conversion
                         cout<<"The value of y="<<y;
                         getch();
                         return 0;
               }
    
               Output:
               The value of y=10

12] Explain type conversion for class type to another class type with example.
  • The class to class conversion is done by both constructor and casting operator.
  • If conversion take place at source class, then by casting operator.
               operator destination_class_name()  //Definition of Casting 
                                                                           operator
               {
                          //Create object of destination class
                          //Write statement to convert value
                          //Return object of destination class
  • If conversion take place at destination class, then by constructor.
           Constructor_of_Destination_Class(Source_class object_name)
            {
                     //Statement for conversion
            }
  • We cannot convert at a time in both source and destination class.
👉Example:
               #include<iostream>
               using namespace std;

               class invent 2;  // destination class declared 
               class invent 1;  // source class
               {
                         int code;          //item code
                         int items;         // no. of items
                         float price;      // cost of each item  
                    public:
                         invent1 ( int a, int b , float c)
                         {
                                   code = a;
                                   items = b;
                                   price = c;   
                         }
                        void putdata()
                        {
                                   cout<<"code:"<<code<<"\n";
                                   cout<<"items:"<<items<<"\n";
                                   cout<<"value:"<<price<<"\n";
                         }
                         int getcode() {return code;}
                         int getitems() {return items;}
                         float getprice() {return price;
                        operator float() {return (items * price;}
               };
               class invent2       // destination class
               {
                         int code;
                         float value;
                    public:
                         invent2 ()
                         {
                                  code = 0; value =0;
                         }
                         invent2(float x, float y)
                         {
                                   code=x;
                                   value =y;
                         }
                         void putdata ()
                        {
                                  cout<<"code:"<<code<<"\n";
                                  cout<<"value:"<<price<<"\n";
                         }
                         invent2(invent1 p)
                         {
                                   code = p.getcode();
                                   value= p.gettimes() *p.getprice();
                         }
               };
               int main()
               {
                         invent s1(100,5,140.0);
                        invent2 d1;
                        float total_value;
                       total_value =s1;
                       d1=s1;
                       cout<<"\nstock value"<<"\n";
                       cout<<"value ="<<total_value<<"\n\n";

                      cout<<"product details-invent2 type"<<"\n";
                      d1.putdata();
                      return 0;
               }
        

                         
                                                 
               

Comments