Sunday, 1 October 2017

How to check Palindrome

Check if a string is palindrome or not is one of most common question we encountered during our basic days.

Let's Solve this problem with a Naive but efficient approach in this case.

Pseudocode :

  1. i=0, j=n
  2. while i < j:
  3.    check if i'th element is not equal to j'th
  4.      then return False 
  5.   else i++,j--
  6. loop end
  7. return True

Monday, 27 June 2016

When to use our own copy constructor while compiler already provides it


Actually compiler provided copy constructor copies all the values of members. So we are using a dynamic allocated member then only address of that member is copied in new object's member. It does not allocate new memory.

  1. #include <iostream>
  2. #include<cstring>
  3. #include<cstdio>
  4. using namespace std;
  5. class XYZ
  6. {
  7.     public:
  8.     char *p;
  9.     XYZ(char *name,int l){
  10.         p=new char[l+1];
  11.         strcpy(p,name);
  12.        
  13.     }
  14. };
  15. int main() {
  16.     XYZ obj1("str",3);
  17.     printf("content of obj1.p is : %u\n",obj1.p);
  18.     XYZ obj2=obj1;
  19.     printf("content of obj2.p is : %u",obj2.p);
  20. }
So here content of member p of obj1 and obj2 is same which is base address of string str
Note that memory is allocated once and pointer to that memory is set for both objects. So default copy constructor only copying members value that is value of obj1.p ( which is address of string "str" ) is copied to obj2.p

Saturday, 25 June 2016

Private Constructor Function and Singleton Pattern

In C++ a constructor can be made private. But what is the use of private constructor ?


Think that you want to create a class in such a way that only one object can be created for this class something called Singleton pattern in C++.
Below is the program to do this.

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class ABC
  4. {
  5.    public:
  6.    int t;
  7.    static ABC creator()
  8.    {
  9.        static ABC x;
  10.        return x;
  11.     }
  12.     private :
  13.     ABC(){ t=10;}
  14. };
  15. int main()
  16. {
  17.     ABC obj1=ABC::creator();
  18.     cout<<" Value of t= "<<obj1.t;
  19.     //ABC obj2=ABC::creator()           returns same object
  20. }


How it works?


Static function are class variable not object's so static function 'creator()' called using class_name::function_name.
Static object is created inside static function. So private constructor function is called which is a valid call since it is from inside of a member function. So obj1 is created and returned.
Next time when we call static function it does not create new object since object is declare as static so same will be returned.
So only one object is created
Blogger Widgets