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";  
     }