Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

Monday, December 16, 2013

How to read file content with out using readline in C++!!

Below is the simple c++ program to read the whole content from file with out using readline function. The idea is, get the size of the file by moving the seek position to the end of the file and allocate the buffer space for the size and read the file content using read function into the allocated buffer.


#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
 ifstream filenumbers;
 filenumbers.open("numbers.txt");
 int length;
 //checks if input file is accessible
 if (!filenumbers) 
 {
 cout << "The input file will not open. Please restart." << endl;
 exit(1);
 }
 // move the position to end of the file
 filenumbers.seekg(0, std::ios::end); 
 // get the current position(now it is at the end of the file so length of the content)
 length = filenumbers.tellg(); 
 // move the position to start of the file 
 //(coming back to start of the file)
 filenumbers.seekg(0, std::ios::beg);
 // allocate memory for a buffer of file size 
 char *buffer = new char[length]; 
 // read whole content of the file into the buffer 
 filenumbers.read(buffer, length); 
 cout<<"buffer is \n"<<buffer;
 filenumbers.close();
 return 0;
}

Output:

buffer is
10
20
30
40
11 2 3 4 5

Saturday, November 23, 2013

How to access a variable from another class in CPP

How to access a variable from another class: We can access the variable from another class by declaring the pointer variable of the class in the class where we want to access the variable. In the below example, we tried to access the data of val which is in the class two and we are trying to set and get the value for the variable val from the class one.


Below is the code in CPP:

#include<iostream>
using namespace std;
class two{
public:
 two(){
 val=0;
 }
 ~two(){
 }
 void setVal(int x){
 val = x;
 }
 int getVal(){
 return val;
 }
private:
 int val;
};
class one{
public:
 two *b;
 one(){
 a = 0;
 b =new two();
 }
 ~one(){
 }
 void setValue(int value)
 {
 b->setVal(value);// = value;
 }
 int getValue()
 {
 return b->getVal();
 }
private:
 int a;
};
int main()
{
 one obj;
 obj.setValue(30);
 cout<<"given value is "<<obj.getValue();
}

Output:
given value is 30

Tuesday, July 31, 2012

how to restrict base class from inheritance!!

In CPP there is a way to restrict the base class from Inheritance. That means , Base class will not allow to create the new derived classes. We can achieve this by making constructor private in the class.
How it works: The basic logic behind this is C++ class access specifier. Derived classes are not allowed to access the private data of the base class. So to create the instance/object of the derived class, it needs base class constructor. So if you make base constructor private, when derived class trying to access the base constructor, it will fail. See the sample code below.

#include<iostream>
using namespace std;
class base
{
//public:
 base()
 {
 cout<<"base constructor\n";
 }
};
class derive:base
{
public:
 derive()
 {
 cout<<"derived constructor\n";
 }
};
main()
{
 derive d;
}

In the above code, In the base class construtor is private and we derived a new class derive. It looks good till now. But the problem is in main() where we created the instance/object of the derive class. Because of base constructor is private, it will throw the below error.

restrict.cpp: In constructor 'derive::derive()':
restrict.cpp:7: error: 'base::base()' is private
restrict.cpp:17: error: within this context

Wednesday, July 4, 2012

delete singleton object in C++ !!

Singleton pattern is used to create only one instance of the class for the application. It will be usefull when you need global resource like Server. Creating the singleton is easy and there wont be any problem. But the problem is when to delete the singleton. It depends on the lifetime of the Singleton.

Method to create the Singleton:
single* single::getInstance()
{
 if(ptr==NULL)
 {
 ptr = new single();
 }
 else
 {
 return ptr;
 }
}
If you want to delete the singleton pointer, dont call the delete on the singleton pointer. Better use some static function like deleteInstance similar to getInstance which used to creat the singleton.

Method to delete the Singleton:
single* single::deleteInstance()
{
 delete ptr;
 ptr = NULL;
}

For single threaded environments it is advised to use a local static varible. So there is no need to use the delete operation. It wont be good for multi threaded environments.
Method to create the Singleton:
single* single::getInstance()
{
 static single sObj;
 return &sObj;
}

P.S: Try to avoid the use of the Singleton as it is a global resource.

Friday, June 29, 2012

Singleton implementation in c++ !!

Below is the implementation of Singleton in C++.
#include<iostream>
using namespace std;
class single
{
 private:
 static single *ptr;
 single()
 {
 }
 public:
 static single* getInstance();
};
single* single::getInstance()
{
 if(ptr==NULL)
 {
 ptr = new single();
 cout<<"creating the instance and address is "<<ptr<<endl;
 }
 else
 {
 cout<<"instance already created address is "<<ptr<<endl;
 return ptr;
 }
}
single* single::ptr=NULL; //initialising the static variable
int main()
{
 single *s,*ss,*sss;
 s=single::getInstance();
 ss=single::getInstance();
 sss=single::getInstance();
}

Tuesday, April 3, 2012

what is virtual table or Vtable in C++?

In C++ for implementing virtual functions , compiler uses Virtual table or simply Vtable. This is also called virtual function table or virtual method table. Lets see what is it and how it works.

As you know virtual functions are used for run time binding or function overriding. If a class contains a virtual function, you will get one virtual table for that class. This applies for derived classes also. So for each class which contains atleast one virtual function, we will be having corresponding Vtable. Compiler create this Vtable at the time of compilation. Vtable is a static array which contians one entry for each virtual fucntion that can be called by object. Each entry in the Vtable is a function pointer to the "most derived" function.

The compiler will also add hidden pointer called *_vptr to the Vtable for the base class. *_vptr will be inherited to the derived class Vtable also. *_vptr pointer adds to the Vtable automatically when instance is creatd. See the below sample code snippet and image for more clarity.

class vtBase
{
 public:
 virtual void display()
 {
 cout<<"this is dispaly function"<<endl;
 }
 virtual void displayMore()
 {
 cout<<"this is dispalyMore function"<<endl;
 }
};
class derivedD:public vtBase
{
 public:
 void display() // display function overriding
 {
 cout<<"this is derived display function"<<endl;
 }
};
class derivedDD:public vtBase
{
 public:
 void displayMore() //displayMore function overriding
 {
 cout<<"this is derived displayMore function"<<endl;
 }
};

In the above code there is base claass vtBase with two virtual functions display() and displayMore(). There are two derived classes in which derivedD is override the function display() with new definition and derivedDD is overrdes the definition for displayMore(). The corresponding Vtable is given below.

Virtual Table
In the above Vtable, base class *_vptr is pointing to the base class vtBase table and its member functions are function pointers to the base class. And derived class *_vptr are pointing to the derived calls Vtable pointer. And in derived class derivedD , you will have two member functions derived from base class, in that one member function display() is overrides with new definition. So its "pointer pointing to the derived member" function and displayMore function "pointer points to the base class" pointer. Similarly for the derived classe derivedDD, but here displayMore() is overrides with new definition. So this function pointer points to derived class and display() function pointer points to the base class.

what happens when object creation:

main()
{
 derivedD D; // creating derived object
 vtBase *bPtr=&D; // assining to base pointer
 bPtr->display();
}

Output:
this is derived display function

In the above main fucntion, in line no. 5, by seeing this, compiler finds display() is virtual function, and then it gets vPtr->display() value as derivedD virtual table from there it looks for the display() function pointer. all this happens in three steps
  • finding function as virtual
  • calling _vptr for getting Vtable address
  • finding the pointer for the function

Using this Vtable process the compiler resolves to the proper virtual function even if you use pointers and references. You can also access the Vtable pointer by using _vptr. see the sample code snippet below.
main()
{
 derivedD D; // creating derived object
 vtBase b; // creating base object
 vtBase *bPtr=&D; // assining to base pointer
 bPtr->display();
 cout<<"_vptr is "<<bPtr->_vptr<<endl; //accessing the _vptr
 bPtr=&b; // assining to base pointer
 bPtr->display();
 cout<<"_vptr is "<<bPtr->_vptr<<endl;//accessing the _vptr
}

Output:
this is derived display function
_vptr is 0x400cb0
this is dispaly function
_vptr is 0x400d30


Monday, April 2, 2012

What is the difference between malloc and new?

This is the regular question generally you will get in C++ Interviews. Both new and malloc are used to allocate the dynamic memory. malloc is used in C and new is used in C++. And the basci difference is new calls the constructor to allocate the memory whereas malloc() is itself is a function and it wont call the constructor. Lets see the differences.

malloc:
  • This is a function
  • It will return the void pointer.
  • Need to type cast to the required data type.
  • It returns NULL if there is no enough memory.
  • It works in C and C++
  • need to use free to deallocate the memory
  • This cann't be overleaded
  • syntax:
void *malloc(size_t size)

  • example:
  • int *ptr;
    ptr = (int *)malloc(10*sizeof(int)); // allocationg 10 bytes of int type
    //do something
    free(ptr); // deallocating the memory
    

new:
  • new is an operator.
  • It calls the constructor while allocating the memory and destructor while deallocating the memory
  • It will return required pointer data type
  • No need to type cast
  • It will return bad exception when there is no enough memory
  • It works only in C++
  • Need to use delete for deallocating the memory
  • its possible to overload the new operator
  • Syntax:
ptr = new typename;
where ptr is pointer of typename(generally class name).
  • example:
  • int *p;
    p = new int; // allocating int datatype
    //do something
    delete p; // for deallocating the memory
    


Thursday, March 29, 2012

Virtual constructors in C++!!

When you try to declare a constructor as virtual in C++ and compile, you will get compile time error saying that "error: constructors cannot be declared virtual". This is because in C++, constructors can't be declared as virtual. lets see why?

Virtual functions in C++ are implementation of run time polymorphism. And they will do function overriding. Generally virtual keyword used in C++ when you need Dynamic behavior. It will work only when object exists. Where as constructors are used to create the objects. Constructors will be called at the time of object creation.

So if you create the constructor as virtual, as per the virtual keyword definition, it should have existing object to use, but constructor is to creating the object, these two will never exists. So should not use the constructor as virtual.

You can use virtual destructors because, at the time of calling destructor, you have the objects. So you can use virtual keyword for the destructors.

Tuesday, March 27, 2012

Virtual destructors in C++

C++ gives default destructor, if you not define the destructor. But this wont be help full if you use dynamic memory allocation. You need to write the destructor function manually to deallocate the memory. This works fine if there is no derived class. If there is any derived class with memory allocation, you should use virtual destructors. see the sample code below.

#include<iostream>
using namespace std;
class base
{
 public:
 base() //constructor
 {
 cout<<"this is base CTOR\n";
 }
 ~base() //not a virtual destructor
 {
 cout<<"this is base DTOR\n";
 }
};
class derived:public base
{
 char *str;
 public:
 derived()
 {
 cout<<"this is derived CTOR\n";
 str = new char[20]; // allocating space
 }
 ~derived()
 {
 cout<<"this is derived DTOR\n";
 delete[] str; // deleting
 }
};
main()
{
 derived *d = new derived(); // creating derived object
 base *b = d; // assigning derived object to base object
 delete b; // deleting base object
}
Output:
this is base CTOR
this is derived CTOR
this is base DTOR

In the above sample code, there is derived class with char pointer member data. Memory is allocated in derived constructor and deallocated in derived destructor. In main() function , derived object is created using new, this is assigned to base object. And base object is deallocated using delete. In the output you got, base constructor, derived constructor, and base destructor. And there is no derived destructor. Actually, we allocated memory in derived constructor. so there is a memory leak, because we are not freed the allocated memory.

To avoid such problems, we need to use virtual destructors. Actually compiler looks for the base destructor and checks for the virtual keyword for the destructor, if it finds virtual keyword, it further goes to derived destructor and goes on till the refered derived class. from there it calls destructor one by one from derived destructor to till it reaches base destructor. If there is no virtual keyword in the base destructor, it stops in base destructor itself. See the sample code with virtual destructor.


Code with virtual destructor:

#include<iostream>
using namespace std;
class base
{
 public:
 base() // base constructor
 {
 cout<<"this is base CTOR\n";
 }
 virtual ~base() // virtual destructor
 {
 cout<<"this is base DTOR\n";
 }
};
class derived:public base
{
 char *str;
 public:
 derived()
 {
 cout<<"this is derived CTOR\n";
 str = new char[20]; // allocating space
 }
 ~derived()
 {
 cout<<"this is derived DTOR\n";
 delete[] str; // deleting
 }
};
main()
{
 derived *d = new derived(); // creating derived object
 base *b = d; // assigning derived object to base object
 delete b; // deleting base object
}

Output:
this is base CTOR
this is derived CTOR
this is derived DTOR
this is base DTOR


In this example, we used virtual destructor, when it calls deleting base pointer, it looks for the base destructor, then it looks for the virtual keyword for the destructor, it will get the keyword, so it looks for the derived destructor, it finds the destructor, and there is no derived classes, so it calls the derived destructor, then it calls the base destructor as shown above. In red color output , is the derived destructor.

Monday, March 26, 2012

Virtual functions in C++!!!

A Virtual function is a special type of function, which resolve to most-derived function with the same prototype. To make a function virtual, just use virtual keyword before the function. This is also called function overriding or runtime polymorphism.

Lets see the use of virtual functions. Assume that there is a base class with one member function. And one derived class with another member function with same name as in base class. If you try to call that member function as shown in the below sample code.

#include <iostream>
using namespace std;
struct base
{
 public:
 void display()
 {
 cout<<"this is base class\n";
 }
};
class derived: public base
{
 public:
 void display() // same function there in base class also
 {
 cout<<"this is derived class\n";
 }
};
int main()
{
 derived d;
 base &b = d; // refering base object to derived object
 b.display();
}

Output:
this is base class


From the above sample code, the expected result should be from derived function as base object is referring to the derived object. But we got the base function. Even though , base object is referring to derived object, it wont resolves to derived class. To avoid this we need to use the virtual keyword. See the same sample code with virtual keyword.

Example With Virtual keyword:

#include <iostream>
using namespace std;
struct base
{
 public:
 virtual void display() // using virtual keyword
 {
 cout<<"this is base class\n";
 }
};
class derived: public base
{
 public:
 void display() //same function is there in base class
 {
 cout<<"this is derived class\n";
 }
};
int main()
{
 derived d;
 base &b = d; // refering base object to derived object
 b.display();
}

Output:
this is derived class


Now we got the expected output, this is because of the virtual keyword. If you use virtual keyword, it will check for resolving function for the derived classes, starting from the base class to referred derived class.

Another Example with more derived classes:
#include <iostream>
using namespace std;
struct base
{
 public:
 virtual void display()
 {
 cout<<"this is base class\n";
 }
};
class derived: public base
{
 public:
 void display()
 {
 cout<<"this is derived class\n";
 }
};
class derived1: public derived
{
 public:
 void display()
 {
 cout<<"this is derived1 class\n";
 }
};
class derived2: public derived1
{
 public:
 void display()
 {
 cout<<"this is derived2 class\n";
 }
};
int main()
{
 base b1;
 derived1 d;
 base &b = d; // base object refering to direved1 object
 b.display();
}

Output:
this is derived1 class


In the above sample code, base object is refering to derived1 object, so resolving process starts from the base class, it checks for the virtual keyword, if it finds the keyword, it goes to the derived class, this process goes on til it reaches the refered object, here it is derived1.

Use of Virtual keyword: To implement virtula functions, we need to use the virtual keyword in base class. And its optional to use in derived class. But its better to use in derived class also, so that you are informing that that function is a virtual function. Generally most base class function need to be used virtual.

Friday, March 23, 2012

Reference variable in C++!!

C++ is a call by reference language. So it supports reference variables. A reference variable is a alias to other variable. The reference variable behaves same like a original variable it is referencing. Reference variable is like a const pointer that is implicitly dereferenced. These variables are declared using ampersand (&). Referance variable should not be NULL. It should refer to some value.

Simple exampe:

#include&lt;iostream>
using namespace std;
main()
{
 int iVar = 10;
 int& rVar = iVar; // declaring the reference variable
 int& rVar1; // illegal , reference variable should refer to some variable
 rVar=20;
 cout<<"ivar is "<<iVar<<endl;
 cout<<"rvar is "<<rVar<<endl;
}
Output:
ivar is 20
rvar is 20

Reference variable is same as normal variable, if you modify the normal , reference variable effects and vice-varsa.

Reference variable can't be redirected: Reference variable cant't be redirected to other variable. i.e. once assigned to a variable cant ba assigned to other variable. See the sample code below.

 int& rVar = iVar; // declaring the reference variable
 int iVar2 =30;
 rVar = iVar2; // it only assigns the value of iVar2 to rVAr

In the above code snippet, rVAr is a reference variable and is referencing to iVar. In the third statement, iVar2 is assigning to rVar. Here it will assign only value. And it will not change the reference variable. It will reference to iVar only.

Constant reference: C++ allows to use constant references. A constant reference will not allow you to change the value it referenced.
 int iVar = 10;
 int const &cVar = iVar; // declaring constant reference variable
 cVar = 40; // illegal, cant change the constant referenc
 iVar = 40; // legal, can change normal variable

Uses of reference pointer:

1. Const reference used as function parameters: As constant reference variables are read only access. It wont allow to modify the value. so passing value as function arguments, it will be vary useful. Constatn reference used in copy constructors for passing object as a argument.


2. Easy access to the nested data: If there are nested data like structure in a structure in as structure. to access the data , we need to use specify each structure variable with dot operator. Using refernce varaible , we can reduce this. See the sample code below.

#include<iostream>
using namespace std;
struct str
{
 int x;
};
struct str1
{
 struct str s;
 int x;
};
struct str2
{
 struct str1 s;
 int x;
};
main()
{
 struct str2 ins;
 ins.x=10;
 ins.s.s.x = 20;
 int &strRef = ins.s.s.x;
 strRef = 40;
 cout<<"strf ref is "<<strRef<<endl;
 cout<<"struct x is "<<ins.s.s.x<<endl;
}

Output:
strf ref is 40
struct x is 40

In the above code, structure str2 member is structrure str1, and its memeber is structure str. To access that , you need to specify all the structure variable with dot operator, instead of this, you can use reference variable to access it as shown in the code.




Thursday, March 22, 2012

Exception handling in C++!!

C++ supports exception handling feature. It will be implemented using try, throw and catch keywords.This is used to exit the application in a proper way after getting the errors like divided by zero or finding the square root of a negative no. or fatal errors. This will throw an error message depending on the error codes.

In C++, exception handling works in such a way that, it looks for the possible errors in try block and if error or exception occurs, it will throw the error. And thrown error in try block will be handled in catch block. Throwing an exception is just jumping the control flow to the catch block when error occurs. After throw statements never execute when exception occurs. Below is simple example.

#include<iostream>
using namespace std;
int main()
{
 try
 {
 throw 3;
 }
 catch(int i)
 {
 cout<<"caught value "<<i<<endl;
 }
 return 0;
}

OutPut:
caught value 3


The above sample code excute the try block, there it throw the numeric value three, so it looks for the corresponding catch block for int , so it displays the message.
Another example by throwing string:

Sampel code for throwing string:
#include<iostream>
#include<math.h>
using namespace std;
main()
{
 try
 {
 int num;
 cout<<"enter the number for square root"<<endl;
 cin>>num;
 if(num<0)
 {
 throw "can't find square root for negative numbers";
 }
 cout<<"sqrt is "<<sqrt(num)<<endl;
 }
 catch( char const *str)
 {
 cout<<str<<endl;
 }
}

Output:
enter the number for square root
4
sqrt is 2

enter the number for square root
-3
can't find square root for negative numbers


Above sample code in try block excutes and check for the condition and throws a constant string when negative no. occurs. After throwing, it looks for the corresponding catch block and displays the messages.

Till now we have seen the example of using throw with in the try block. But most of the cases are different, where throwing an exception is not in try block. So what exactly compiler does is that, it will check for immidiate catch block , if not , it will send to its caller function, there it checks for the catch block and goes on till it reaches corresponding catch block or till it reaches main function. This process is called stack unwinding.

Example for stack unwinding:

#include<iostream>
using namespace std;
void fun2()
{
 throw "throwing exception in func2\n";
}
void fun1()
{
 cout<<"in fun1()\n";
 try
 {
 fun2();
 }
 catch(char *)
 {
 cout<<"exception caught in fun1\n"<<endl;
 }
}
void display()
{
 cout<<"in display()\n";
 fun1();
}
main()
{
 try
 {
 cout<<"in main function\n";
 display();
 }
 catch(char const*str )
 {
 cout<<"exception caught in main \" "<<str<<"\""<<endl;
 }
}

OutPut:
in main function
in display()
in fun1()
exception caught in main " throwing exception in func2"

In the above sample code, main function calls display() and it calls fun1() and it calls fun2(), fun2() throws exception with constant string, but fun2() don't have catch block, so it returns to its caller fun1(), fun1() is having catch() block, but it is not a constant string , so it returns its caller fun(), fun() don't have catch block, it returns to its caller main(). main has its corresponding catch block, so exception caught in main function.


What happens if no matching catch block: Generally compiler looks for the matching catch block. If there is no catch block, application terminates with a error message depending on the compiler. In GNU C++ compiler the error message is "terminate called after throwing an instance of" for no matching catch for exceptions. To avoid such cases C++ provides a default catch block with (...) three consecutive dots in a catch. If you have no idea what to throw, just use default throwing three dots (...) similar to default catch.

Sample code for no matcing catch block:

#include<iostream>
using namespace std;
int main()
{
 try
 {
 throw 3;
 }
 catch(char )
 {
 cout<<"caught exception "<<endl;
 }
 return 0;
}
OutPut:
terminate called after throwing an instance of 'int'
Aborted

In the above code, try block throwing int value, but there is no catch block to handle int value, so it will abort the process with the error message as shown in the output.
Sample code for default catch block:
#include<iostream>
using namespace std;
int main()
{
 try
 {
 throw 3;
 }
 catch(...)
 {
 cout<<"caught exception "<<endl;
 }
 return 0;
}
OutPut:
caught exception

In above samle code, try block throws int exception, but there is no int catch block,there is a default catch block to handle any exception.

Monday, March 19, 2012

What is STL in C++?

The Standard Template Library or simply STL is a container classes, algorithms and iterators of the C++ library. A container is object which contains the collection of the objects. These are implemented as a template classes. Before going into STL, better get the knowledge of Template classes in C++. The STL's are classified into following groups.

Container Classes:

1. Sequence Containers:
  • Vector: This is like dynamic array of variables, structs or objects. We can insert the data at the end. we can access the data using indexing. see the example below.
  • De queue: Similar to array, and we can insert the data at the beginning and end. In this also we can access the data using indexing.
  • List: Similar to linked list. We can add/delete the data from anywhere.
2. Container Adaptors:
  • Stack: Same as Stack data structure. It uses LIFO concept.
  • Queue: Same as queue data structure. It uses FIFO concept.
  • Priority queue: Is a special adopter container, which contains the elements such a way that first element of the container is always greater.
3. Associative Adaptors:
  • Set : is a collection of ordered data in a balanced binary tree structure. And duplicate values are not allowed in SET
  • Multi Set: Same as SET, except duplicate values are allowed.
  • Map: is a collection of associated key-value pair in a balanced binary tree structure. And duplicate keys are not allowed.
  • Multi Map: Same as Map except, duplicate keys are allowed in multi-maps.

Operations/Utilities on STL:

  • Iterator: This is used identify the elements in STL using position. This is also used to access the elements in the STL.
  • Algorithm: This is used to apply the function like find, sort, count, search on STL.
  • Auto_ptr : This is used for avoiding memory leaks. Using this , we can allocate the memory and no need of freeing the memory. auto_ptr will delete the allocated memory automatically after its use.

Vector Example:

#include<iostream>
#include<vector>
using namespace std;
// need to include corresponding STL header file. e.g vector file for vector STL
main()
{
 vector<int> v; // declaring the vector STL. similar to template
 for (int i =0;i<5;i++)
 v.push_back(10*i); // adding the element at the end
 vector<int>::iterator ii; // declaring the iterator
 for(ii=v.begin();ii<v.end();ii++)
 cout<<*ii<<" "; // accessing the value using iterator
}
Output:
0 10 20 30 40

Stack Example:

#include<iostream>
#include<stack>
using namespace std;
main()
{
 stack<int> st; // declaring stack STL
 for (int j=0;j<5;j++)
 st.push(j*10); // pushing the element into the stack
 while(!st.empty()) // checking for empty stack
 {
 cout<<" "<<st.top(); // getting the top of the stack element
 st.pop(); // deleting the element from the stack
 }
}
Output:
40 30 20 10 0


Friday, March 16, 2012

Templates in C++ !!

Assume that there is a scenario where you need to find the max of two integers, double and char's. So you will write three different max functions for each. Here the code for all functions are same, the only difference is datatype. To avoid such a duplicate code , C++ supports a feature called Templates. Using templates, we can write a generic function which works for all data types. There are two types of templates namely function templates and class templates.
The syntax is given below. It starts with template keyword followed by enclosing either class or typename keyword and generic type name in <, > and followed by function defintion. Both syntax's works similarly. There is no difference.

Syntax:
template <class generic_type [class generic_type] [class generic_type]>
function_definition

Function templates: A function template is like a normal function only, except the arguement type. A single function defintion works for different data types. A function will not store in memory. Actual function definition will be generated at the time of compilation basing on the data type.


Example:

using namespace std;
template <typename T>
T add(T a,T b)
{
 return (a+b);
}
main()
{
cout<<"2+3 is "<<(add(2,3))<<"\n";
cout<<"2.3+2.3 is "<<(add(2.3,2.3))<<"\n";
//cout<<"2+2.3 is "<<(add(2,2.3))<<"\n"; Illegal , arguments for the add function should be same type.
}
OutPut:
2+3 is 5
2.3+2.3 is 4.6

Class Template: Is a class in which member data are generic data types.See the below sample code .

using namespace std;
template <typename T>
class tmp{
 public:
 T a,b;
 tmp(T x, T y):a(x),b(y)
 {
 cout<<"a n b are "<<a<<" "<<b<<endl;
 }
};
int main()
{
tmp<int> o(2,3);
tmp<double> a1(2.3,3.4);
}

OutPut:
a n b are 2 3
a n b are 2.3 3.4

Thursday, March 8, 2012

What is smart pointer?

The main problems with pointers in C/C++ is handling memory managment. Most of the bugs related to memory leaks and dangling pointers. To overcome this C++ supports smart pointers. The smart pointer is a object similar to pointer. Smart pointer supports all basic operations like dereferencing(operator *), indirection (operator ->) and below features which pointer doesn't support.

Automatic deallocation: Smart pointer deallocates/cleanup the allocated memory automatically using destructor.
Automatic initialisation: No need to initialise the pointer to NULL. smart pointer will take care using constructor
Handling Dangling pointers: One of the main problem in C/C++ is handling dagling pointer. i.e. accessing the pointer that is pointing to the another object which is already deleted. Smart pointers will take care about dangling pointers.

P.S: Simple example for the smart pointers in C++ is auto_ptr which is a part of C++ standard library. And the header file is .

Wednesday, March 7, 2012

How to declare/access the pointer variable inside the class in C++?

Declaring the pointer variable inside the class is similar to normal C declaration only. While allocating the memory and access the variable will differ. It will be good to have a memory allocation in constructor and deallocation in destructor. See the sample code below for more clarity.

In the below sample code, there is class ptr with one integer data member i and one integer pointer data member p. These are initialised in constructor using new for pointer variable. In destructor used delete for freeing the dynamic memory. For accessing the pointer data using the instance P and O as saind in main().

*P->p gives the value of the variable and not P->*p. Where as P->p gives the address of the pointer variable. Similarly for object O, *O.p gives the value of the variable and not O.*p. Where as O.p gives the address of the pointer variable.

using namespace std;
class ptr
{
 public:
 int i;
 int *p;
 ptr();
 ~ptr();
};
ptr::ptr() // constructor
{
 i=10;
 p=new int;
 *p = 20;
}
ptr::~ptr() //destructor
{
 delete p;
}
int main()
{
 ptr *P=new ptr(); //dynamic instance
 cout<<"P->i is "<<P->i<<endl; //accessing normal variable
 cout<<"P->p is "<<P->p<<endl; // will get address of the poitner variable
 cout<<"*P->p is "<<*P->p<<endl; // accessing the pointer variable. P->*p is a invalid expression
 ptr O; //static instance
 cout<<"O.i is "<<O.i<<endl; //accessing normal int variable
 cout<<"O.p is "<<O.p<<endl; // will get the address of the int pointer
 cout<<"*O.p is "<<*O.p<<endl; //accessing the poiner variable. O.*p is a invalid expression
}

Output:

P->i is 10

P->p is 0xfda4030
*P->p is 20

O.i is 10
O.p is 0xfda4050
*O.p is 20

Tuesday, March 6, 2012

What is the difference between Struct and class in C++?

The basic difference between struct and class in C++ is that by default all data member functions and member variabels are private in class where as in struct it is public. Except this every thing is same for struct and class. All C++ concepts like polymorphism, inheritance etc works fine with struct also.

Basic example:

struct structClass
{
 int x; // defualt public
 public:
 structClass();
};
structClass::structClass() // constructor
{
 x=0;
}
class classC
{
 int x; //defualt private
 public:
 classC();
};
classC::classC() // constructor
{
 x=0;
}
int main()
{
 structClass sC;
 sC.x =10; // Legal as it is a struct and not a class
 classC cC;
// cC.x = 10; // Illegal as it is a class and default specifier is private
}

Example for Inheritance:
struct base
{
 public:
 virtual void display()
 {
 cout<<"this is base class\n";
 }
};
class derived: public base
{
 public:
 void display()
 {
 cout<<"this is derived class\n";
 }
};
int main()
{
 base b1;
 derived d;
 base &b = d;
 b.display();
}
In the above sample code, base class is of type structure and derived class is of type c++ class. This also works fine in C++.

Monday, March 5, 2012

What is mutable variable in C++??

There are some cases where data members are declaring as const, and later want to change the value of the const variable.In C++, it is not legal to change the const value, by using mutable it is possible.This keyword can be applied to only non-static and non-constant data members.

Example for changing constant object data member:

class mute{
public:
int x ;
mutable int y; // mutable variable declaration
mute() // constructor
{
x=10;
y=10;
}
};
int main()
{
const mute m; // constant object
//m.x=20; // Illegal cant change the data members in a constant object
m.y=20; // Legal, we can change , because its a mutable
}
For the above sampel code, there is class mute with one int and one mutable int data member functions. There is constant object for the class. If you try to modify the normal data members here it is x in line no.16, we will get compilation error. But we can modify the mutable data , here it is y in line no.17.

Example for changing the constant function data:
class mute{
public:
int x ;
mutable int y;
mute()
{
x=10;
y=10;
}
void setValue(int a) const
{
//x=a; // Illegal, cant change the values in constant function
y=a; // legal, mutable data allowed to change in constant functions
}
};
int main()
{
mute m;
m.setValue(5);
}

In the above sample code, where we are changin the data members using constant functions. In line no.14, if you try to change the normal variable in constant function it will throuh an error. But if you see in line no.15 , its perfectly legal to change the mutable varaible in constant function.

Wednesday, February 29, 2012

How to initialize const variable in C++?

In C++, const keyword is used to create the one time initializer and read-only variable. Once intialised, it is not legal to change the value later. There are two ways to initiaze the const varaibles in C++.
Example:
class cns
{
 private:
 const int val; // declaring const variable
 const static int st=10; //declaring n initializing using static keyword
 public:
 cns(int aa = 0) :val(aa) // initializing using initialization list
 {
 }
};
main()
{
 cns con(10);
}

P.S: if const variables are not initialised, the values are undefined and it will not allow to change the values. So it is mandatory to initialize the const variables.

Tuesday, February 28, 2012

What is initialization list in C++?

Generally in C++, we will initalise the variables in constructors using assignment operator. But there are some scenarios like const and reference variables, where we need to initialise at the time of declaration. Assignement operator will not work for these. C++ provides new feature initialisation list to do this. The initialisation list is required in inheritance and compostion for initialising data members.
The Initialisation list should add after the constructor, starts with a colon (:) and each variable with the value enclosed in brackets and separated by comma. It will not end with semicolon(;). If you use initialisatin list, no need off explicit assignment of the variables in constructor. See the sample code below.

class inList{
 private:
 int x,y;
 public:
 inList():x(10),y(20) //initialisation list
 {
 //nothing
 }
 inList(int aX, int aY):x(aX),y(aY) // initialization list
 {
 //nothing
 }
};
int main()
{
 inList l;
 inList iL(100,200);
}

the above two constructors are same as below.

inList()
{
 x=10;
 y=20; 
}
inList(int aX, int aY)
{
 x=aX;
 y=aY;
}

Example for Inheritance:

class inList{
 private:
 public:
 int x,y;
 inList():x(10),y(20)
 {
 //nothing
 }
 inList(int aX, int aY):x(aX),y(aY)
 {
 //nothing
 }
};
class inListDerive: public inList
{
 private:
 int z;
 public:
 inListDerive():z(10),inList(20,30)
 {
 //nothing
 }
 inListDerive(int aZ):z(aZ),inList(20,30)
 {
 //nothing
 }
};
int main()
{
 inListDerive dL; 
 inListDerive dL1(100);
}

P.S: To see initialising const variable using initialisation list click here.
Subscribe to: Comments (Atom)

Popular Posts

AltStyle によって変換されたページ (->オリジナル) /