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.

Object Oriented Programming Basic QA

Define object oriented language?
Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.

The programming challenge was seen as how to write the logic, not how to define the data. Object-oriented programming takes the view that what we really care about are the objects we want to manipulate rather than the logic required to manipulate them. Examples of objects range from human beings (described by name, address, and so forth) to buildings and floors (whose properties can be described and managed) down to the little widgets on your computer desktop (such as buttons and scroll bars).

Define object based language?
The term "object-based language" may be used in a technical sense to describe any programming language that uses the idea of encapsulating state and operations inside "objects". Object-based languages need not support inheritance or subtyping, but those that do are also said to be "object-oriented". Object-based languages that do not support inheritance or subtyping are usually not considered to be true object-oriented languages.

Few examples of object-oriented languages are Smalltalk, C++, Python, Ruby, Java, C#. An example of a language that is object-based but not object-oriented is Visual Basic (VB). VB supports both objects and classes, but not inheritance, so it does not qualify as object-oriented.

Define procedure oriented language?
The procedure oriented programming (POP) approach focuses on creating and ordering procedures or a block of code keeping in mind to accomplish a specific job. The key features of this kind of approach are: use of procedures, sequencing of procedures and sharing global data.
characteristics of Procedure Oriented Language are:
  • IT uses Top Down Programming approach in program design. The main task is divided into sub task and functions.

  • All function share the data through global variable.

  • Data is less secure as it is available to all functions.

  • Procedural Language gives more importance to instruction and less importance to data.

List the disadvantage of Procedure oriented programming?

  1. No security for data. If we declare a variable before main function then it can be accessed freely from any function present in the program.

  2. No better memory management.

  3. Difficult to implement today's client requirements.

  4. No structure or code reusability. Hence time of development, testing and length of program increases.

  5. As length of application increases it causes slow performance.

  6. Code maintenance and enhancements are difficult.

  7. No proper way method for Exception handling.

What are the advantages of a object oriented language over the procedural language?
  • In object oriented language everything is object and dynamic where as in procedural you have to follow sequence for programs and implementation.

  • Procedural language does not have extra packaging like object oriented.

  • If you wish to save a lot of code through reusable components and frameworks and designs, it's best to use an object oriented paradigm in your solution.
List the Advantages of an object-oriented language in organization?
These are some of the major advantages of OOP.
  • Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear.

  • Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system.

  • Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods.

  • Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.

  • Maintainability: objects can be maintained separately, making locating and fixing problems easier.

  • Re-usability: objects can be reused in different programs.
State the important object oriented features
Some of the important object oriented features are namely:
  • Objects

  • Classes

  • Inheritance

  • Data Abstraction

  • Data Encapsulation

  • Polymorphism

  • Overloading

  • Reusability

What is inheritance?
Inheritance is the process of forming a new class from an existing class or base class. The base class is also known as parent class or super class, The new class that is formed is called derived class. Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code size of the program,by reusing the parent class members.

Whats is data abstraction?
Data Abstraction increases the power of programming language by creating user defined data types. Data Abstraction also represents the needed information in the program without presenting the details. Class is a construct for abstract data types (ADT).

What is Data Encapsulation?
Data Encapsulation combines data and functions into a single unit called Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the functions present inside the class. Data Encapsulation enables the important concept of data hiding possible.

Whats is Polymorphism?
Polymorphism allows routines to use variables of different types at different times. An operator or function can be given different meanings or functions. Polymorphism refers to a single function or multi-functioning operator performing in different ways.

Whats is Reusability?
This term refers to the ability for multiple programmers to use the same written and debugged existing class of data. This is a time saving device and adds code efficiency to the language. Additionally, the programmer can incorporate new features to the existing class, further developing the application and allowing users to achieve increased performance. This time saving feature optimizes code, helps in gaining secured applications and facilitates easier maintenance on the application.

What is overloading?
In programming languages, a feature that allows an object to have different meanings depending on its context. The term is used most often in reference to operators that can behave differently depending on the data type, or class, of the operands. For example, x+y can mean different things depending on whether x and y are simple integers or complex data structures.

Not all programming languages support overloading but it is a feature of most object-oriented languages, including C++ and Java. Overloading is one type of polymorphism.

What is Method overriding?
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.[1] 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

C++ Basic interview questions on class and objects

What is a class?
A class in C++ is an encapsulation of data members and functions that manipulate the data. A class is a mechanism for creating user-defined data types.
Classes are generally declared using the keyword class, with the following format:
class ExampleClass
{
};
here ExampleClass is the name of the class.

What is an object?
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
class ExampleClass
{
};
int main()
{
ExampleClass obj1; // obj1 is the instance of the class ExampleClass
}

What is Aggregate class?
An aggregate class is a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.[2] Such a class can be initialized with a brace-enclosed comma-separated list of initializer-clauses.

class Aggregate
{
public:
int a;
double b;
};
int main()
{
Aggregate obj = {5, 10.25};
}

What are the ways of creating a class?
Classes can be defined not only with keyword class, but also with keywords struct and union.
The concepts of class and data structure are so similar that both keywords (struct and class) can be used in C++ to declare classes (i.e. structs can also have function members in C++, not only data members).
The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access. For all other purposes both keywords are equivalent.
The concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold function members. The default access in union classes is public.

What is Constructor?
Constructors in C++ are special member functions of a class. They have the same name as the Class Name. There can be any number of overloaded constructors inside a class, provided they have a different set of parameters. There are some important qualities for a constructor to be noted.

  • Constructors have the same name as the class.

  • Constructors do not return any values.

  • Constructors are invoked first when a class is initialized. Any initializations for the class members, memory allocations are done at the constructor.

  • If the constructor is declared as private, then the class cannot be instantiated.
class Example
{
public:
Example(){
cout<<"i am default constructor\n";
}
Example(int a){
cout<<"i am overloaded constructor\n";
}
};
here Example() is the default constructor.And Example(int a) is an overloaded constructor which takes one interger argument.

What is Destructor?
Destructors in C++ also have the class name, except for the fact that they are preceded by a '~' operator.
The destructors are called when the object of a class goes out of scope.
It is not necessary to declare a constructor or a destructor inside a class. If not declared, the compiler will automatically create a default one for each.
If the destructor is declared as private, then the class cannot be instantiated.
class Example
{
public:
Example(){
cout<<"i am default constructor\n";
}
Example(int a){
cout<<"i am overloaded constructor\n";
}
};

Tell something about C++ union?

  • A C++ union is a limited form of the class type.

  • It can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors.

  • It cannot contain virtual functions or static data members.

  • It cannot be used as a base class, nor can it have base classes.

  • Default access of members in a union is public.

What is the difference between C++ class and struct?
There is no difference between a class and a struct except that by default, the members of a struct are public, and the members of a class are private.
Also structs are by default inherited publicly and classes by default are inherited privately. Other than that, whatever you can do in a class, you can do in a struct.

Explain the below code?
struct A
{
int a;
};
class B:A
{
int b;
};
int main()
{
B obj;
obj.a = 10; // compilation error
}
error: `int A::a' is inaccessible
The GNU project C++ compiler is consistent with 11.2.2 of ISO/IEC 14882-2003, which states that the kind of inheritance is determined by the derived class being declared as a class or struct when an access specificer for the base class is absent.

What is the difference between class and object?
Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.

  • A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.

  • The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.

  • An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.