DISHA NIRDESHAN

Enlightens your career

Tuesday, June 21, 2011

Difference among various concepts


 Major Differences Between C And C++

 

                                      C

                                    C++

C follows the procedural programming paradigm

C++ is a multi-paradigm language(procedural as well as object oriented)

 

In case of C, importance is given to the steps or procedure of the program

C++ focuses on the data rather than the process.
Also, it is easier to implement/edit the code in case of C++ for the same reason.

. In case of C, the data is not secured

the data is secured(hidden) in C+

C is a low-level language

C++ is a middle-level language

 

C uses the top-down approach

C++ uses the bottom-up approach

 

C is function-driven

&  Functions are the building blocks of a C program

C++ is object-driven & objects are building blocks of a C++ program.

 

 

We cannot   use function inside the structure

We can use function inside the structure 

 

C uses scanf & printf

C++ uses cin>> & cout<<

C doesnot allows reference varaibles

C++ allows the use of reference variables

 

 

 

 

Difference between a copy constructor and an assignment operator.  

 

Copy Constructor

Assignment Operator

                                                                                                                                                                             

Copy constructor creates a new object which has the copy of the original object. 

 

 

On the other hand assignment operators does not create any new object. It instead, deals with existing objects.

 

Difference between "C structure" and "C++  Structure".


                 or

Define classes and structure.

 

 

                            Class

                      Structure

User defined data type which contains data and methods to manipulate that data; is known as class.

A structure is a collection of variables, referenced under one name, providing a convenient means of keeping related information together.

Each object is associated with the data of type class with which it is created.

Structure declaration forms a template which can be used to create structure objects.

An object is a variable of a Class.

variables inside a structure are called members.

Class declaration precedes the keyword Class.

 

Structure declaration precedes the keyword struct.

 

Eg.
class Student
{
           int rollno;
           int marks1, marks2;
           public:
                      void show(int r); // to print marks
                      void sum(int r); // to add the marks
};

 

example:

struct address
{
            char name[80];
            char street[80];
            char city[20];
            char state[20];
};

 

 


Other Concepts


Other Concepts:

What is an Object? What is Object Oriented Programming?

Object represents/resembles a Physical/real entity. An object is simply something you can give a name. Object Oriented Programming is a Style of programming that represents a program as a system of objects and enables code-reuse.

 

What are C++ storage classes?

auto:the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition(when they are out of scope). They are not visible  outside that block
       

auto int a;
         int b; Both are same statement. auto is default register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance(Generally Used in loops)
static:a variable that is known only within the  function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution

     void example()
    { 
        static int a = 0; // static variable  
        a++;
        cout << a <<endl;
   }

   If this function is called 10 times, the output will be 1,2,3,4...etc., The value of the variable a is preserved through function calls.    If this static variable is declared as a member of a class, then it will preserve the value for all the objects of the class.i.e, one copy of this data variable will be shared by all objects of the class

What is a scope resolution operator?

A scope resolution operator (::), can be used to define the member functions of a class outside the class.

 

 

 

Association :

Association is a relationship where all object have their own lifecycle and there is no owner. Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.


Aggregation:

 Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object cannot belongs to another parent object. Let's take an example of Department and teacher. A single teacher cannot belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about "has-a" relationship.

Composition:

 Composition is again specialize form of Aggregation and we can call this as a "death" relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let's take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belongs to two different house if we delete the house room will automatically delete. Let's take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

 

 


Questions on Exceptional handling & polymorphism


 

EXCEPTION HANDLING:

What is an Exceptional Handling?

An exception is a hardware generated condition which is triggered when processing fails for some reason in a CPU. It could be caused by dividing by zero or trying to access memory at a nonexistent address

The exception handling mechanism is made up of the following elements:

 

ü try blocks

ü catch blocks

ü throw expressions

ü Exception specifications (C++ only)

 

The benefits of Exception Handling are:

1. Program is not terminated abruptly
2. User will understand what errors are occurring in the program.

The three keywords for Exception Handling are:
Try, Catch and Throw.

The program tries to do something. If it encounters some problem, it throws an exception to another program block which catches the exception.

 

Consider following program code:
void main()
{
               int no1, no2;
               try
               {
                       cout << "Enter two nos:";
                       cin >> no1 >> no2;
                       if (no2 == 0)
                              throw "Divide by zero";
                       else
                              throw no1/no2;
               }
               catch (char *s)
               {
                          cout << s;
               }
               catch (int ans)
               {
                          cout << ans;
               }
}

We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed.

After an exception has been handled the program execution resumes after the try-catch block, not after the throw statement!.

 

 

Explain about Rethrowing exceptions with an example.  

Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. This causes current exception to be passed on to an outer try/catch sequence. An exception can only be rethrown from within a catch block. When an exception is rethrown, it is propagated outward to the next catch block.

Consider following code:

#include <iostream>
using namespace std;
void MyHandler()
{
        try
        {
                 throw "hello";
        }
        catch (const char*)
        {
               cout <<"Caught exception inside MyHandler\n";
               throw; //rethrow char* out of function
        }
}
int main()
{
            cout<< "Main start";
            try
            {
                   MyHandler();
            }
            catch(const char*)
            {
                  cout <<"Caught exception inside Main\n";
            }
                  cout << "Main end";
            return 0;
}
O/p:
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();

 

What are the tow types of Exceptions?

Exceptions are of two types:

Synchronous Exceptions: Errors that occur due to incorrect input data or incorrect handling of array indices ("out of range index"), memory overflow are known as Synchronous Exceptions

Asynchronous Exceptions: The errors that are caused by events that are beyond control of the program are Asynchronous Exceptions. E.g. Keyboard interrupts

C++ exception handling mechanism takes care of only Synchronous Exceptions.

 

 

 

 

 

 

POLYMORPHISM:

What is Polymorphism?

 

Polymorphism is the ability to provide single interface to multiple implementation it may be for an or function in different ways. Polymorphism gives different meanings or functions to the operators or functions. A single function usage or an operator functioning in many ways can be called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts.
There are two types of polymorphism
1. Compile Time Polymorphism (Static Polymorphism)
2. Run Time Polymorphism (Dynamic Polymorphism)

1. Compile time polymorphism

Compile time polymorphism is a term that refers to C++ template programming. For example, at compile time you determine the actual type of a std::vector by what it contains:

std::vector  vi;
std::vector std::string> vs;

or function Overloading is the example of compile time polymorphism

2. Run Time Polymorphism (Dynamic Polymorphism)
Virtual function is the example of Run Time polymorphism. At the run time base class pointer decide whether to call the base class function or the derived class function.

 

 

How is it that polymorphism enables you to program "in the general" rather than "in the specific." Discuss the key advantages of programming "in the general." ?

Polymorphism enables the programmer to concentrate on the processing of common operations that are applied to all data types in the system without going into the individual details of each data type. The general processing capabilities are separated from the internal details of each type.

 

Discuss the problems of programming with switch logic. Explain why polymorphism is an effective alternative to using switch logic. ?

The main problem with programming using the switch structure is extensibility and maintainability of the program. A program containing many switch structures is difficult to modify. Many, but not necessarily all, switch structures will need to add or remove cases for a specified type.

Encapsulation:

What is Encapsulation?

1. The wrapping up of data and member function into a single unit is called encapsulation.

2. The data is not accessible to the outside world and only those functions which are wrapped into a class can access it.

                                      Or

Encapsulation is binding of attributes and behaviors. Hiding the actual implementation and exposing the functionality of any object. Encapsulation is the first step towards OOPS, is the procedure of covering up of data and functions into a single unit (called class). Its main aim is to protect the data from outside world

 

 

 

 Adding a new method with the same name in same/derived class but with different number/types of parameters. It implements Polymorphism.

 

What is Abstraction?

Hiding the complexity. It is a process of defining communication interface for the functionality and hiding rest of the things.


What is Overloading?

Specifying  more than one definition for a function name or an operator in the same scope is called Overloading

There are tow types of Overloading:

ü Operator overloading

ü Function Overloading

 

Operator overloading

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.

The following set of operators is commonly overloaded for user-defined classes:

  • = (assignment operator)
  • + - * (binary arithmetic operators)
  • += -= *= (compound assignment operators)
  • == != (comparison operators)

 

Function Overloading

It is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters. Consider the following function:

1

int Add(int nX, int nY)

2

{

 

3

    return nX + nY;

4

}

This trivial function adds two integers. However, what if we also need to add two floating point numbers? This function is not at all suitable, as any floating point parameters would be converted to integers, causing the floating point arguments to lose their fractional values.

One way to work around this issue is to define multiple functions with slightly different names:

1

int AddI(int nX, int nY)

2

{

 

3

    return nX + nY;

4

}

 

5

 

6

double AddD(double dX, double dY)

 

7

{

8

    return dX + dY;

 

9

}

However, for best effect, this requires that you define a consistent naming standard, remember the name of all the different flavors of the function, and call the correct one (calling AddD() with integer parameters may produce the wrong result due to precision issues).

Function overloading provides a better solution. Using function overloading, we can declare another Add() function that takes double parameters:

1

double Add(double dX, double dY)

2

{

 

3

    return dX + dY;

4

}

We now have two version of Add():

1

int Add(int nX, int nY); // integer version

2

double Add(double dX, double dY); // floating point version

Which version of Add() gets called depends on the arguments used in the call — if we provide two ints, C++ will know we mean to call Add(int, int). If we provide two floating point numbers, C++ will know we mean to call Add(double, double). In fact, we can define as many overloaded Add() functions as we want, so long as each Add() function has unique parameters.

Consequently, it's also possible to define Add() functions with a differing number of parameters:

1

int Add(int nX, int nY, int nZ)

2

{

 

3

    return nX + nY + nZ;

4

}

Even though this Add() function has 3 parameters instead of 2, because the parameters are different than any other version of Add(), this is valid.

 

 

 

 

What is Overriding ?

A process of creating different implementation of a method having a same name as base class, in a derived class. It implements Inheritance.

 

 


Questions on Inheritance

INHERITANCE

What is inheritance, explain with an example?

Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them

#include <iostream>
using namespace std;

class BaseClass {
  int i;
public:
  void setInt(int n);
  int getInt();
};

class DerivedClass : public BaseClass {
  int j;
public:
  void setJ(int n);
  int mul();
};

void BaseClass::setInt(int n)
{
  i = n;
}

int BaseClass::getInt()
{
  return i;
}

void DerivedClass::setJ(int n)
{
  j = n;
}

int DerivedClass::mul()
{
  return j * getInt();
}

int main()
{
  DerivedClass ob;

  ob.setInt(10);        // load i in BaseClass
  ob.setJ(4);          // load j in DerivedClass

  cout << ob.mul();     // displays 40

  return 0;
}

 

 

What is a base class? Explain with an example using C++.

 

 

#include <iostream>
using namespace std;

class BaseClass {
  int i, j;
public:
  void set(int a, int b) { 
     i = a; 
     j = b; 
  }
  void show() { 
     cout << i << " " << j << endl; 
  }
};

class DerivedClass : public BaseClass {
  int k;
public:
  DerivedClass(int x) { 
     k = x; 
  }
  void showk() { 
     cout << k << endl; 
  }
};

int main()
{
  DerivedClass ob(3);

  ob.set(1, 2); // access member of BaseClass
  ob.show();    // access member of BaseClass

  ob.showk();   // uses member of DerivedClass class

  return 0;
}

 

How do we implement inheritance in C++?  

The inheritance feature in C++ is implemented in the following manner:
class Square: public Shape
{
        ...
};

In the above example all public members of Shape can be reused by the class Square. If public key word is left, private inheritance takes place by default. If protected is specified the inheritance is applied for any descendant or friend class.

 

What is Base Class?

The base class is the highest class and does not inherit from any other class. Other classes can inherit from a base class. They are called derived classes.

 

class A {
  public:
    int x;
};
class B : public A {
  public:
    int y;
};
class C : public B { };

 

Explaination:

Class A is base class

 

What are Direct Base class and indirect base class?

 

A direct base class is a base class that appears directly as a base specifier in the declaration of its derived class.

An indirect base class is a base class that does not appear directly in the declaration of the derived class but is available to the derived class through one of its base classes. For a given class, all base classes that are not direct base classes are indirect base classes. The above example demonstrates direct and indirect base classes:

Class B is a direct base class of C. Class A is a direct base class of B. Class A is an indirect base class of C. (Class C has x and y as its data members.)

 

 

What is private, public and protected Inheritance?  

Private Inheritance
The Public and protected members of Base class become private members of the derived class.

When a class is being derived from another class, we can make use of access specifiers. This is essentially useful to control the access the derived class members have to the base class. When inheritance is private:

·         i. Private members of base class are not accessible to derived class.

·         ii. Protected members of base class become private members of derived class.

·         iii. Public members of base class become private members of derived class.

 

Public Inheritance
All the public members and protected members are inherited as public and protected respectively.

Protected Inheritance
Public and Protected members are derived as protected members.

When a class is being derived from another class, we can make use of access specifiers. This is essentially useful to control the access the derived class members have to the base class. When inheritance is protected:

·         Private members of base class are not accessible to derived class.

·         Protected members of base class remain protected in derived class.

·         Public members of base class become protected in derived class.

Questions on Constructors

 

CONSTRUCTORS QUESTIONS

 

 

What is a constructor? 

A constructor allocates space for an object and initializes it. Constructors always have the same name as their class. A class may have more than one constructor.

Or

Constructors allow initialization of objects at the time of their creation. Constructor function is a special function that is a member of the class and has same name as that of the class. An object's constructor is automatically called whenever the object is created (statically or dynamically). Constructors are always public. They are used to make initializations at the time of object creation.

 

What is Destructors?

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.

                                                Or

Destructors are complements of constructors. When an object is destroyed, its destructor is automatically called. Destructors are mainly useful for doing the clean up job. E.g. an object may have allocated some memory during its lifetime; destructors are the place where this memory is deallocated. Or an object may need to close some files by releasing its handles which it had previously obtained.

Destructor function has same name as that of a constructor; but the name is preceded by a tilde ('~') sign.

Example
Student::~Student() {
     Age = 0;
    
}

 

 

 

What is virtual constructors/destructors?

The explicit destroying of object with the use of delete operator to a base class pointer to the object is performed by the destructor of the base-class is invoked on that object.

 

Explain default constructor or what is a default constructor?

A constructor with no arguments or all the arguments has default values.

What is copy constructor?

Creation of an object as a copy of an existing object us know as copy constructor

What is a conversion constructor?

It is a constructor that accepts one argument of a different type.

 

What are the restrictions apply to constructors and destructors?  

The following restrictions apply to constructors and destructors

1.     Constructors and destructors don't return values.

2.     The addresses of constructors and destructors can't be taken so we can't use references and pointers on them.

3.     Constructors cannot be declared with the keyword virtual.

4.     Constructors and destructors cannot be declared static, const, or volatile.

Explain the order in which constructors are called when an object of a derived class is created.  

The constructors of any virtual base classes are called first in the order of inheritance.
Non-virtual base class constructors are called next.
The derived class constructor is called last.

What is a virtual destructor? Explain the use of it.  

If the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.

Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.

class x
{
           public:          
           x(){printf("\nBase Constructor\n");}
           ~x(){printf("\nBase Destructor\n");} 
};

class y : public x 
{
         public:
         y(){printf("\nDerived Constructor\n");}
         ~y(){printf("\nDerived Destructor\n");} 
};
int main()
{
         x* object=new y;
         delete object;
         return 0;
}

Output:
Base Constructor
Derived Constructor
Base Destructor

By Changing
~x(){printf("\nBase Destructor\n");}
to
virtual ~x(){printf("\nBase Destructor\n");}

 

Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor

 

 

Can constructors have parameters?

Yes, constructors can have parameters. so we can overload it.