Monday, July 30, 2012

C++ Basic Questions Part - 2


Q : What is constructor in C++?

A : A constructor is a function that initializes the members of an object. A constructor only knows how to build an object of its own class.
Some points about constructors
  • Constructors are just functions with the same name as the class.
  • Constructors are intended to initialize the members of the class when an instance of that class is created.
  • Constructors are not called directly (except through initializer lists).
  • Constructors are never virtual.
  • Multiple constructors for the same class can be defined. They must have different parameters to distinguish them.




  • Q : What is destructor in C++?

    A : A destructor is a class member function that has the same name as the constructor (and the class ) but with a ~ (tilde) in front. Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
  • A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const, volatile, const volatile or static. A destructor can be declared virtual or pure virtual.
  • If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor. This implicitly declared destructor is an inline public member of its class.



    Q : What is copy constructor?

    A : A copy constructor is a special constructor in the C++ programming language for creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed (const or non-const), which might be followed by parameters of any type (all having default values).
    Normally the compiler automatically creates a copy constructor for each class (known as a default copy constructor) but for special cases the programmer creates the copy constructor, known as a user-defined copy constructor. In such cases, the compiler does not create one. Hence, there is always one copy constructor that is either defined by the user or by the system.



    Q : What is Assignment operator?

    A : In the C++ programming language, the assignment operator, '=', is the operator used for assignment. Like most other operators in C++, it can be overloaded. The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a member-wise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).



    Q : Why do we need to write a copy constructor?

    A : The implicit copy constructor does a member-wise copy of the source object. In many cases, this is sufficient. However, there are certain circumstances where the member-wise copy version is not good enough. By far, the most common reason the default copy constructor is not sufficient is because the object contains raw pointers and you need to take a "deep" copy of the pointer. That is, you don't want to copy the pointer itself; rather you want to copy what the pointer points to. Why do you need to take "deep" copies? This is typically because the instance owns the pointer; that is, the instance is responsible for calling delete on the pointer at some point (probably the destructor). If two objects end up calling delete on the same non-NULL pointer, heap corruption results.



    Q : Why do we need to write an assignment operator?

    A : First, you should understand that if you do not declare an assignment operator, the compiler gives you one implicitly. The implicit assignment operator does member-wise assignment of each data member from the source object. Default assignment operator is not sufficient is because the object contains raw pointers and you need to take a "deep" copy of the pointer. That is, you don't want to copy the pointer itself; rather you want to copy what the pointer points to. Why do you need to take "deep" copies? This is typically because the instance owns the pointer; that is, the instance is responsible for calling delete on the pointer at some point (probably the destructor). If two objects end up calling delete on the same non-NULL pointer, heap corruption results.



    Q : When do we need to write an assignment operator?

    A : If your object has a pointer to dynamically allocated memory, eg allocated in the constructor, you will want to make a deep copy of the object. Deep copies require overloading assignment, as well as defining a copy constructor and a destructor).



    Q: When copy constructors are called?

    A : A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment). The following cases may result in a call to a copy constructor:
  • When an object is returned by value.
  • When an object is passed (to a function) by value as an argument.
  • When an object is thrown.
  • When an object is caught.
  • When an object is placed in a brace-enclosed initializer list.
  • These cases are collectively called copy-initialization.



    Q : What is shallow copy?

    A : A shallow copy means that C++ copies each member of the class individually using the assignment operator. When classes are simple (eg. do not contain any dynamically allocated memory), this works very well. But may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. But the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.



    Q : What is deep copy?

    A : A deep copy duplicates the object or variable being pointed to so that the destination (the object being assigned to) receives it’s own local copy. This way, the destination can do whatever it wants to it’s local copy and the object that was copied from will not be affected. Doing deep copies requires that we write our own copy constructors and overloaded assignment operators.



    Q: When and what should I do for deep copy?

    A : If an object has pointers to dynamically allocated memory, and the dynamically allocated memory needs to be copied when the original object is copied, then a deep copy is required.
    A class that requires deep copies generally needs:
  • A constructor to either make an initial allocation or set the pointer to NULL.
  • A destructor to delete the dynamically allocated memory.
  • A copy constructor to make a copy of the dynamically allocated memory.
  • An overloaded assignment operator to make a copy of the dynamically allocated memory.




  • Q : What is Lazy copy?

    A : A lazy copy is a combination of both strategies above. When initially copying an object, a (fast) shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify an object, it can determine if the data is shared (by examining the counter) and can do a deep copy if necessary. Lazy copy looks to the outside just as a deep copy but takes advantage of the speed of a shallow copy whenever possible.



    Friday, July 27, 2012

    C++ Basic Questions Part - 1


    Q : What is OOP?

    A: Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP.





    Q : What is Data abstraction?

    A: Data abstraction refers to, providing only essential information to the outside word and hiding their background details ie. to represent the needed information in program without presenting the details.
    C++ classes provides great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data ie. state without actually knowing how class has been implemented internally.




    Q : What is Abstract Data Type (ADT)?

    A: Abstract data type (ADT) is a specification of a set of data and the set of operations that can be performed on the data.
    In C++ we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like following:
     #include <iostream>  
     using std::cout;  
     int main( )  
     {  
       cout << "Hello World \n";  
       return 0;  
     }  
    

    Here you don't need to understand how cout displays the text on the user's screen. You need only know the public interface and the underlying implementation of cout is free to change.




    Q : What is Encapsulation?

    A: Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
    C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. C++ Class can contain private, protected and public members. By default, all items defined in a class are private.
    Example:
     #include <iostream>  
     using std::cout;  
     class Example  
     {  
      private:  
       int a;  
      public:  
       void display(){  
        cout<<"Value of a :"<<a;  
       }  
     };  
    
    The variables 'a' is private. This means that it can be accessed only by other members of the Example class, and not by any other part of your program. This is one way encapsulation is achieved.
    Make class members private by default unless we really need to expose them. That's just good encapsulation.




    Q : What is the difference between Data Encapsulation and Data Abstraction?

    A: Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.




    Q : What is Modularity?

    A : One obvious way to reduce chaos and introduce some order into any complex project is to divide it into reasonably independent pieces. A large, well-structured software system typically comprises a number of modules that can be created and tested independently of each other. Each module implements a set of related data structures and functions. Modern programming languages and software development environments, including C++, provide support for this modular approach.
    The benefits of modular software design, besides cleaner structure and more efficient implementation, include easier software maintenance and reusability. In a bird's-eye view of the project, each module exists to carry out a certain task. Once the interfaces between the modules are defined, each module can be implemented and even modified independently of the other modules. This property is called locality. A tested module can be used in other projects that present the same task. This property is called reusability. Since software's main costs are development and maintenance, not physical production, tested reusable code is essentially free.




    Q : What is polymorphism?

    A : The word polymorphism means having many forms.In programming languages, polymorphism means that some code or operations or objects behave differently in different contexts.
    In C++ polymorphism can be achieved by following ways
  • Inheritance and virtual methods.
  • Function overloading
  • Function overriding





  • Q : What is Inheritance ?

    A : One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
    When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

    syntax : class derived_class: access_specifier base_class

    Example :

     #include <iostream>  
     using std::cout;  
     class Base  
     {  
       public:  
       void BaseFunction(){  
          cout<<"This is Base class Function\n";  
       }  
     };  
     class Derived : public Base  
     {  
       public :  
         void DerivedFunction(){  
           cout<<"This is Derived class Function\n";  
        }  
     };  
    

    Here class Derived is derived from class Base.




    Q : what are Access Specifiers?

    A : There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
  • Public - The members declared as Public are accessible from outside the Class through an object of the class.
  • Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
  • Private - These members are only accessible from within the class. No outside Access is allowed.





  • Q : Tell something about Inheritance and Access Specifiers?

    A : A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class. We can summarize the different access types according to who can access them in the following way:
    Accesspublicprotectedprivate
    Same class yes yes yes
    Derived classes yes yes no
    Outside classes yes no no

    A derived class inherits all base class methods with the following exceptions:
  • Constructors, destructors and copy constructors of the base class.
  • Overloaded operators of the base class.
  • The friend functions of the base class.





  • Q : What are the types of Inheritance?

    A : When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. The type of inheritance is specified by the access-specifier as explained above.

    We hardly use protected or private inheritance but public inheritance is commonly used. While using different type of inheritance, following rules are applied:

  • Public Inheritance: When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
  • Protected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.
  • Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.





  • Q : What is Multiple Inheritance?

    A : You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance.
    Example:
     class A { /* ... */ };  
     class B { /* ... */ };  
     class C { /* ... */ };  
     class X : public A, private B, public C { /* ... */ };  
    

    The following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow:

    The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors. A direct base class cannot appear in the base list of a derived class more than once:
     class B1 { /* ... */ };          // direct base class  
     class D : public B1, private B1 { /* ... */ }; // error  
    





    Q : What is Method/Function overriding?

    A : Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.
    Example :

     class Base  
     {  
       public:  
          void display()  
          {  
            std::cout<<"Base Display\n";  
          }  
     };  
     class Derived : public Base  
     {  
       public:  
          void display()  
          {  
            std::cout<<"Derived Display\n";  
          }  
     };  
     int main()  
     {  
       Base *obj = new Derived();   
       obj->display(); // Base Display printed  
       Derived *obj2 = new Derived();   
       obj2->display(); // Derived Display printed  
     }  
    





    Q : What is Method/Function Overloading?

    A : Function overloading is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters.
    Function overloading allows creating several methods with the same name which differ from each other in the type and number of the input of the function. It is simply defined as the ability of one function to perform different tasks.
    For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.
    Example :

     int add(int a , int b)  
     {  
       return a+b; //Adds two integers and returns int  
     }  
     string add(string a , string b)  
     {  
       return a+b; //concatenates two strings and returns string  
     }  
    




    C++ Quiz Programs Part - 1

    Q : is the following program valid? Yes/No give the reason.

     #include <iostream>  
     using namespace std;  
     int main()  
     {  
          int ____123 =123;  
          cout <<"Hello World! "<<____123<<"\n";  
          return 0;  
     }  
    
    A : Yes the above program is valid. in C & C++ identifier name can/should start with _ or [a-zA-Z]. It cant contain any space or special characters in it.



    Q : Write a program to add two numbers without using assignment operator.

    A : Remember when we were kids we used to add numbers one by one counting the fingers. Example 5 + 4 = 5 + 1 = 6 + 1 = 7 + 1 = 8 + 1 = 9 . Simple problem solved :) Add one by one in a loop using ++ operator.
     #include<iostream>  
     using namespace std;  
     int main()  
     {  
          int a,b;  
          cout<<"Enter Two Numbers :";  
          cin >>a>>b;  
          while(b--)++a;  
          cout<<"Result :"<<a<<endl;  
     }  
    



    Q : in C++ can a have Anonymous class?

    A : In C++ classes can be anonymous ie., they can be declared without an identifier.
     #include<iostream>  
     using std::cout;  
     class{  
          private:  
               int a;  
          public:  
               void init()  
               {  
                    a=10;  
               }  
               void display()  
               {  
                    cout<<"i m display() - member function "<<a<<"\n";  
               }  
     }A,B;  
     int main()  
     {  
          A.init();  
          A.display();  
          B.display();  
     }  
    

    Output:
    i m display() - member function 10
    i m display() - member function 0

    Here A and B are the instance of the anonymous class. Member functions of anonymous classes can be called like normal class member functions.

    Anonymous classes comes with some restrictions.

  • They can't have constructor or destructor [ofcourse they don't have a name].
  • They can't be passed as a function argument. Even if we pass them as an argument to a function with Ellipses, it will abort at runtime. But the compiler wont complain any error as Ellipses skips type checking.
  • They cannot be returned as return values from functions.
  • No class can inherit from anonymous class, Remember they don't have name



  • Q : Inheritance and Anonymous class is it valid?

    A : Yes. Check the below program
     #include<iostream>  
     #include <stdarg.h>  
     using std::cout;  
     class Base  
     {  
        public:  
            int a;  
            Base():a(7){}  
            void parentDisplay(){  
                   cout<<"Parent Class value of a :"<<a<<"\n";  
              }  
     };  
     class : public Base  
     {  
        public:  
           void childDisplay()  
           {  
              cout<<"Child Class - ";  
              parentDisplay();  
           }  
     } AnonymousInherited;  
     int main()  
     {  
          AnonymousInherited.parentDisplay();  
          AnonymousInherited.childDisplay();  
     }  
    

    Output:
    Parent Class value of a :7
    Child Class - Parent Class value of a :7



    Q : Tell something about anonymous union?

    A : Union can be anonymous. But we should know the restrictions of anonymous unions. They are
  • They can't have constructor and destructor.
  • Anonymous unions can't have member functions.
  • Anonymous unions can't be inherited from any other union.

  • Example:
     #include<iostream>  
     using std::cout;  
     int main()  
     {  
       union Base  
       {  
         int x;  
       };  
          union : Base // Error here  
          {  
               int a;  
               char c;  
               void display(){cout<<" a : "<<a<<"\n";} // Error here  
          };  
          a = 97;  
          cout<<" c : "<<c<<"\n";  
     }  
    



    Thursday, June 9, 2011

    C++ Difference between xxxx and yyyy

    Difference Between Malloc and Calloc

    There are two differences. First, is in the number of arguments. Malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments (number of variables to allocate memory, size in bytes of a single variable). Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
    Here are more opinions and answers:
    • Calloc(m, n) is essentially equivalent to p = malloc(m*n); memset(p, 0, m*n); The zero fill is all-bits-zero, and does not therefore guarantee useful null pointer values or floating-point zero values. 'Free' is useable to release the memory allocated by malloc or calloc.

    • Malloc(s); returns a pointer for enough storage for an object of s bytes. Calloc(n,s); returns a pointer for enough contiguous storage for n objects, each of s bytes. The storage is all initialized to zeros.

    • Simply, malloc takes a single argument and allocates bytes of memory as per the argument taken during its invocation. Where as calloc takes two aguments, and calculates their product.
    Difference Between C++ vector and List
    • A vector is a set of sequentially arranged data that can grow or shrink dynamically; a list is a set of linked items that are not necessarily sequentially arranged in memory.

    • With a vector, you have random access to any element in constant time, as well as adding elements to the end of the vector in constant time. However, insertions and deletions take more time, proportionate to the number of subsequent or previous elements that need to be 'pushed down' or 'moved back' to make room for the new element or to contract the vector into the just 'emptied' slot.
      With a list, you don't have random access (you must 'follow the links' to reach any element), but insertions and deletions are done in constant time.

    • List support bi-directional iterators while vector uses random access iterator.

    • Vectors grow dynamically as items are added to them. When a vector grows, it doubles the number of items it can contain. This can force the entire vector to be moved to another spot in memory, which can be computationally expensive. Lists do not need to store their elements contiguously in memory, and can therefore grow or shrink one item at a time without ever needing to copy the entire list to a new location.
    Difference between c structure and c++ structure
    • In C++ it is allowed to define functions as part of a struct where as you can not define function in C structures.

    • C++ struct supports inheritance where as C struct don't have the concept of inheritance

    • C struct dont't have access limitations(data hiding) such as public, private or protected. Where as C++ struct have access limitations , the default access specifier is public

    • struct keyword is required in C while creating a structure variable, whereas in C++ it is not required.

    • In C sizeof empty struct is 0, whereas in C++ sizeof empty struct is 1.

    Difference between C++ struct and class
    • Members of a class are private by default, whereas members of a struct are public by default.

    • Inheritance between classes is also private by default, and inheritance between structs is public by default.

    • Note: The kind of inheritance is determined by the derived class being declared as a class or struct when an access specifier for the base class is absent.
    Difference between C++ Interface and Abstract class
    • An abstract class is a class that has at least one pure virtual function, thus cannot be instantiated directly. An interface class would basically be an abstract class that is composed entirely of pure virtual functions.

    • An interface defines no methods (just declares them) and holds absolutely no private data while an abstract class can do them both.

    • An Abstract class lets you define some behaviors and force your subclasses to provide others. An interface is a contract, a specification that concrete classes MUST follow. It defines method signatures but cannot have any implementations; the latter must be provided by the classes that implement the interface.
    Difference between C bool and C++ bool

    The C language does not have a boolean type. Instead, it uses integer under the following general rules:
    1. An operation which requires a boolean value takes an integer and treats zero as false and any other value as true.

    2. An operation which produces a boolean value generates 1 or 0 for true and false.
    The C++ committee eventually added a boolean type to C++ (and called it bool, just to keep you from spelling right the first time). To maintain compatibility with C, it converts freely to and from integer under similar rules. Specifically:
    1. When an integer is used in a boolean context, it is converted under similar rules: zero becomes false, and nonzero becomes true.

    2. When a bool is used in an int context, it is converted to 1 or 0, for true or false.
    Difference between C++ inline functions and macros

    Inline functions are similar to macros because they both are expanded at compile time, but the macros are expanded by the preprocessor, while inline functions are parsed by the compiler. There are several important differences:
    • Inline functions follow all the protocols of type safety enforced on normal functions.

    • Inline functions are specified using the same syntax as any other function except that they include the inline keyword in the function declaration.

    • Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once.

    • Macros are always expanded by preprocessor whereas compiler may or may not replace the inline definitions.

    • Inline functions respect scope and can be put in a namespace.

    • Inline functions can be overloaded.

    • You can use the address of an inline function (e.g. as a functor).

    • macros are expanded at pre-compile time, you cannot use them for debugging, but you can use inline functions.

    • Because macros are expanded by the preprocessor, if incompatible types are passed compiler error messages will refer to the expanded macro, rather than the macro definition itself.

    Thursday, June 2, 2011

    All about Pointers to Members

    A class can have two general categories of members: function members and data
    members. Likewise, there are two categories of pointers to members: pointers to
    member functions and pointers to data members. The latter are less common because
    in general, classes do not have public data members. However, when using legacy C
    code that contains structs or classes that happen to have public data members, pointers to data members are useful.
    Pointers to member functions are one of the most intricate syntactic constructs in C++, and yet, they are a very powerful feature too. They enable you to invoke a member function of an object without having to know the name of that function. This is very handy implementing callbacks. Similarly, you can use a pointer to data member to examine and alter the value of a data member without knowing its name.

    Pointers to Data Members:

    Although the syntax of pointers to members may seem a bit confusing at first, it's consistent and resembles the form of ordinary pointers, with the addition of the class name followed by the operator :: before the asterisk. For example, if an ordinary pointer to int looks as follows:
    int * pi;
    You define a pointer to an int member of class A as follows:
    int A::*pmi; /* pmi is a pointer to an int member of A*/
    You initialize a pointer to member like this:
    class A
    {
    public:
    int num;
    int x;
    };
    int A::*pmi = & A::num; /* 1 */
    The statement numbered 1 declares a pointer to an int member of class A and initializes
    it with the address of the member num. Using pmi and the built-in operator .* you can
    examine and modify the value of num in any object of class A:
    A a1, a2;
    int n=a1.*pmi; /* copy a1.num to n */
    a1.*pmi=5; /* assign the value 5 to a1.num */
    a2.*pmi=6; /* assign the value 6 to a2.num */
    If you have a pointer to A, you need to use the built-in operator ->* instead:
    A * pa=new A;
    int n=pa->*pmi;
    pa->*pmi=5;

    Pointers To Member Functions:

    These consist of the member function's return type, the class name followed by ::, the pointer's name, and the function's parameter list. For example, a pointer to a member function of class A that returns an int and takes no arguments is defined as follows (note that both pairs of parentheses are mandatory).
    class A
    {
    public:
    int func ();
    };
    int (A::*pmf) ();
    In other words, pmf is a pointer to a member function of class A that returns int and
    takes no arguments. In fact, a pointer to a member functions looks as an ordinary
    pointer to function, except that it also contains the class's name immediately followed by the :: operator. You can invoke the member function to which pmf points using operator .*:
    pmf=&A::func;
    A a;
    (a.*pmf)(); /* invoke a.func() */
    If you have a pointer to an object, you use the operator ->* instead:
    A *pa=&a;
    (pa->*pmf)(); /*calls pa->func() */
    Pointers to member functions respect polymorphism. Thus, if you call a virtual member
    function through such a pointer, the call will be resolved dynamically. Note, however, that you can't take the address of a class's constructor and destructor.

    C++ important Tips

    Difference between < iostream.h > or < iostream >?
    Many C++ programmers still use instead of the newer, standard
    compliant library. What are the differences between the two? First, the .h
    notation of standard header files was deprecated more than five years ago. Using
    deprecated features in new code is never a good idea. In terms of functionality,
    contains a set of templatized I/O classes which support both narrow and
    wide characters, as opposed to which only supports char-oriented
    streams. Third, the C++ standard specification of iostream's interface was changed in
    many subtle aspects. Consequently, the interfaces and implementation of
    differ from those of . Finally, components are declared in
    namespace std whereas components are global.
    Because of these substantial differences, you cannot mix the two libraries in one
    program. As a rule, use unless you're dealing with legacy code that is only compatible with .

    Binding a Reference to an Rvalue
    Rvalues and lvalues are a fundamental concept of C++ programming. In essence, an
    rvalue is an expression that cannot appear on the left-hand side of an assignment
    expression. By contrast, an lvalue refers to an object (in its wider sense), or a chunk of memory, to which you can write a value. References can be bound to both rvalues and lvalues. However, due to the language's restrictions regarding rvalues, you have to be aware of the restrictions on binding references to rvalues, too.
    Binding a reference to an rvalue is allowed as long as the reference is bound to a const type. The rationale behind this rule is straightforward: you can't change an rvalue, and only a reference to const ensures that the program doesn't modify an rvalue through its reference. In the following example, the function f() takes a reference to const int:
    void f(const int & i);
    int main()
    {
    f(2); /* OK */
    }
    The program passes the rvalue 2 as an argument to f(). At runtime, C++ creates a
    temporary object of type int with the value 2 and binds it to the reference i. The
    temporary and its reference exist from the moment f() is invoked until it returns; they are destroyed immediately afterwards. Note that had we declared the reference i
    without the const qualifier, the function f() could have modified its argument, thereby causing undefined behavior. For this reason, you may only bind references to const objects.
    The same rule applies to user-defined objects. You may bind a reference to a temporary object only if it's const:
    struct A{};
    void f(const A& a);
    int main()
    {
    f(A()); /* OK, binding a temporary A to a const reference*/
    }

    Comma-Separated Expressions
    Comma-separated expressions were inherited from C. It's likely that you use such
    expressions in for- and while-loops rather often. Yet, the language rules in this regard are far from being intuitive. First, let's see what a comma separated expression is.
    An expression may consist of one or more sub-expressions separated by commas. For
    example:
    if(++x, --y, cin.good()) /*three expressions*/
    The if condition contains three expressions separated by commas. C++ ensures that
    each of the expressions is evaluated and its side effects take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression.
    Therefore, the if condition above evaluates as true only if cin.good() returns true. Here's another example of a comma expression:
    int j=10;
    int i=0;
    while( ++i, --j)
    {
    /*..repeat as long as j is not 0*/
    }

    Calling a Function Before Program's Startup
    Certain applications need to invoke startup functions that run before the main program starts. For example, polling, billing, and logger functions must be invoked before the actual program begins. The easiest way to achieve this is by calling these functions from a constructor of a global object. Because global objects are conceptually constructed before the program's outset, these functions will run before main() starts. For example:
    class Logger
    {
    public:
    Logger()
    {
    activate_log();
    }
    };
    Logger log; /*global instance*/
    int main()
    {
    record * prec=read_log();
    //.. application code
    }
    The global object log is constructed before main() starts. During its construction, log invokes the function activate_log(). Thus, when main() starts, it can read data from the log file.

    Hiding the Cumbersome Syntax of Pointers to Functions
    Can you tell what the following declaration means?
    void (*p[10]) (void (*)());
    p is an "array of 10 pointers to a function returning void and taking a pointer to another function that returns void and takes no arguments." The cumbersome syntax is nearly indecipherable, isn't it? You can simplify this declaration considerably by using typedefs.
    First, declare a typedef for "pointer to a function returning void and taking no
    arguments" as follows:
    typedef void (*pfv)();
    Next, declare another typedef for "pointer to a function returning void and taking a pfv":
    typedef void (*pf_taking_pfv) (pfv);
    Now declaring an array of 10 such pointers is a breeze:
    pf_taking_pfv p[10]; /*equivalent to
    void (*p[10]) (void (*)()); but much more readable*/

    Wednesday, June 1, 2011

    Can you access private variables outside the class?

    You think you can't access private data members outside the class. you are wrong !
    Using pointer arithmetic we can achieve this.
    Create a class with private data member. Create an abject for that class. The size of the object will be size of all data members + 4(if it has any virtual functions). Also the order of member declaration is important.
    By creating the pointer to memory locations in the object we can access the variable. For example consider the following program.

     #include<iostream>  
    using std::cout;
    class A
    {
    Private:
    int a;
    public:
    A():a(10)
    {
    }
    };
    int main()
    {
    A obj;
    cout<<"Sizeof(obj):"<<sizeof(obj)<<"\n";
    int *ptr = (int*)&obj;
    cout<<"a :"<<*ptr<<"\n";
    *ptr = 4;
    cout<<"a :"<<*ptr<<"\n";
    }

    Here “a” is a private variable. Size of int is 4, so the size of “obj” is 4. By creating integer pointer to the object we can access the private variable “a”. Compile and run the above program to see the result. Although it is bad idea to access private variables using pointer arithmetic, this tutorial is indented to show we can access private variables.