Showing posts with label C Programming. Show all posts
Showing posts with label C Programming. Show all posts

October 15, 2013

Differences Between Java and C++

All Differences Between Java and C++ 

Pointers
Java does not have an explicit pointer type. Instead of pointers, all references to objects—
including variable assignments, arguments passed into methods, and array elements—are
accomplished by using implicit references. References and pointers are essentially the same thing
except that you can’t do pointer arithmetic on references (nor do you need to).
Reference semantics also enable structures such as linked lists to be created easily in Java without
explicit pointers; merely create a linked list node with variables that point to the next and the
previous node. Then, to insert items in the list, assign those variables to other node objects.


Arrays
Arrays in Java are first class objects, and references to arrays and their contents are accomplished
through explicit references rather than via point arithmetic. Array boundaries are strictly
enforced; attempting to read past the ends of an array is a compile or run-time error. As with
other objects, passing an array to a method passes a reference to the original array, so changing
the contents of that array reference changes the original array object.
Arrays of objects are arrays of references that are not automatically initialized to contain actual
objects. Using the following Java code produces an array of type MyObject with ten elements, but
that array initially contains only nulls:
MyObject arrayofobjs[] = new MyObject[10];
You must now add actual MyObject objects to that array:
for (int i; i< arrayofobjs.length. i++) {
arrayofobjs[i] = new MyObject();
Java does not support multidimensional arrays as in C and C++. In Java, you must create arrays
that contain other arrays.
 

Strings
Strings in C and C++ are arrays of characters, terminated by a null character (\0). To operate
on and manage strings, you treat them as you would any other array, with all the inherent
difficulties of keeping track of pointer arithmetic and being careful not to stray off the end of
the array.

Strings in Java are objects, and all methods that operate on strings can treat the string as a
complete entity. Strings are not terminated by a null, nor can you accidentally overstep the end
of a string (like arrays, string boundaries are strictly enforced).


Memory Management
All memory management in Java is automatic; memory is allocated automatically when an
object is created, and a run-time garbage collector (the “GC”) frees that memory when the object
is no longer in use. C’s malloc and free functions do not exist in Java.
To “force” an object to be freed, remove all references to that object (assign variables holding
it to null, remove it from arrays, and so on). The next time the Java GC runs, that object is
reclaimed.


Data Types
As mentioned in the early part of this book, all Java primitive data types (char, int, long, and
so on) have consistent sizes and behavior across platforms and operating systems. There are no
unsigned data types as in C and C++ (except for char, which is a 16-bit unsigned integer).
The boolean primitive data type can have two values: true or false. Boolean is not an integer,
nor can it be treated as one, although you cannot cast 0 or 1 (integers) to boolean types in Java.
Composite data types are accomplished in Java exclusively through the use of class definitions.
The struct, union, and typedef keywords have all been removed in favor of classes.
Casting between data types is much more controlled in Java; automatic casting occurs only when
there will be no loss of information. All other casts must be explicit. The primitive data types
(int, float, long, char, boolean, and so on) cannot be cast to objects or vice versa; there are
methods and special “wrapper” classes to convert values between objects and primitive types.


Operators
Operator precedence and association behaves as it does in C. Note, however, that the new
keyword (for creating a new object) binds tighter than dot notation (.), which is different
behavior from C++. In particular, note the following expression:
new foo().bar;
This expression operates as if it were written like this:
(new foo()).bar;
Operator overloading, as in C++, cannot be accomplished in Java. The , operator of C has been
deleted.
The >>> operator produces an unsigned logical right shift (remember, there are no unsigned data
types).
The + operator can be used to concatenate strings.


Control Flow
Although the if, while, for, and do statements in Java are syntactically the same as they are in
C and C++, there is one significant difference. The test expression for each control flow construct
must return an actual boolean value (true or false). In C and C++, the expression can return
an integer.


Arguments
Java does not support mechanisms for optional arguments or for variable-length argument lists
to functions as in C and C++. All method definitions must have a specific number of arguments.
Command-line arguments in Java behave differently from those in C and C++. The first element
in the argument vector (argv[0]) in C and C++ is the name of the program itself; in Java, that
first argument is the first of the additional arguments. In other words, in Java, argv[0] is argv[1]
in C and C++; there is no way to get hold of the actual name of the Java program.


The following other minor differences from C and C++ exist in Java: 
  •  Java does not have a preprocessor, and as such, does not have #defines or macros. Constants can be created by using the final modifier when declaring class and instance variables.
  •  Java does not have template classes as in C++.
  •  Java does not include C’s const keyword or the ability to pass by const reference explicitly.
  •  Java classes are singly inherited, with some multiple-inheritance features provided through interfaces.
  •  All functions are implemented as methods. There are no functions that are not tied to classes.
  •  The goto keyword does not exist in Java (it’s a reserved word, but currently unimplemented). You can, however, use labeled breaks and continues to break out of and continue executing complex switch or loop constructs.

October 09, 2013

c / c++ Interview Questions



Question- What is a register variable?
Answer- Register variables are stored in the CPU registers. Its default value is a garbage value. Scope of a register variable is local to the block in which it is defined. Lifetime is till control remains within the block in which the register variable is defined. Variable stored in a CPU register can always be accessed faster than the one that is stored in memory. Therefore, if a variable is used at many places in a program, it is better to declare its storage class as register
 

For Example:
register int x=5;
Variables for



Question-     What’s the difference between COM and DCOM? 
Answer- the question does not require strict answer. Any DCOM object is yet a COM object (DCOM extends COM) and any COM object may participate in DCOM transactions. DCOM introduced several improvements/optimizations for distributed environment, such as MULTI_QI (multiple QueryInterface()), security contexts etc. DCOM demonstrated importance of surrogate process (you cannot run in-proc server on a remote machine. You need a surrogate process to do that.) DCOM introduced a load balancing.

Question- Where is an auto variables stored?
Answer- Main memory and CPU registers are the two memory locations where auto variables are stored. Auto variables are defined under automatic storage class. They are stored in main memory. Memory is allocated to an automatic variable when the block which contains it is called and it is de-allocated at the completion of its block execution.
Auto variables:
Storage           :             main memory.
Default value  :             garbage value.
Scope             :             local to the block in which the variable is defined.
Lifetime          :             till the control remains within the block in which the variable is defined.



Question- What is a node class? 
Answer- A node class is a class that,
o    relies on the base class for services and implementation,
o    provides a wider interface to the users than its base class,
o    relies primarily on virtual functions in its public interface
o    depends on all its direct and indirect base class
o    can be understood only in the context of the base class
o    can be used as base for further derivation
o    can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class. 
 
Question- What is an orthogonal base class? 
Answer- If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

April 29, 2013

C, C++ Interview Questions And Answers

In C++, what is the difference between method overloading and method overriding?
Ans- Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.


What methods can be overridden in Java?  
Ans-  In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.


In C, what is the difference between a static variable and global variable?
Ans- A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).


In C, why is the void pointer useful? When would you use it? 
Ans- The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.


What are the defining traits of an object-oriented language? 
Ans- The defining traits of an object-oriented langauge are:
           encapsulation
            inheritance 
            polymorphism     

C/C++ Programming interview questions and answers

What is the difference between a pointer and a reference? Ans- A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.


How are prefix and postfix versions of operator++() differentiated?
Ans- The postfix version of operator++() has a
dummy parameter of type int. The prefix version does not have dummy parameter.


What is name mangling in C++??
Ans- The process of encoding the parameter types with the function/method name into a unique name is called name mangling. The inverse process is called demangling.
For example Foo::bar(int, long) const is mangled as `bar__C3Fooil'.
For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as `__C3Fooil'.


What is the difference between const char *myPointer and char *const myPointer?
Ans- Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.


How can I handle a constructor that fails?
Ans- throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

C/C++ Programming interview questions and answers

Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
Ans- C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.



Name two cases where you MUST use initialization list as opposed to assignment in constructors.
Ans- Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.



Can you overload a function based only on whether a parameter is a value or a reference?
Ans- No. Passing by value and by reference looks identical to the caller.



What are the differences between a C++ struct and C++ class?
Ans- The default member and base class access specifiers are different.
The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.



What does extern "C" int func(int *, Foo) accomplish?
Ans- It will turn off "name mangling" for func so that one can link to code compiled by a C compiler.



How do you access the static member of a class?
Ans- <ClassName>::<StaticMemberName>

C/C++ Programming interview questions and answers

What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?
Ans- Multiple Inheritance is the process whereby a child can be derived from more than one parent class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name.


What are the access privileges in C++? What is the default access level?
Ans- The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.



What is a nested class? Why can it be useful?
Ans- A nested class is a class enclosed within the scope of another class. For example:
  //  Example 1: Nested class
  //
  class OuterClass
  {
    class NestedClass
    {
      // ...
    };
    // ...
  };
Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass. Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's members and friends can use NestedClass.
When you instantiate as outer class, it won't instantiate inside class.





What is a local class? Why can it be useful?
Ans- local class is a class defined within the scope of a function -- any function, whether a member function or a free function. For example:
  //  Example 2: Local class
  //
  int f()
  {
    class LocalClass
    {
      // ...
    };
    // ...
  };
Like nested classes, local classes can be a useful tool for managing code dependencies.



Can a copy constructor accept an object of the same class as parameter, instead of reference of the object? 
Ans- No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

C/C++ Programming interview questions and answers

What is a container class? What are the types of container classes?
Ans- A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the
container is called a homogeneous container.


What is inline function?? 
Ans- The __inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler's discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline. 


What is overloading??
Ans- With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope.
- Any two functions in a set of overloaded functions must have different argument lists.
- Overloading functions with argument lists of the same types, based on return type alone, is an error.


What is Overriding?
Ans- To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.
The definition of the method overriding is:
· Must have same method name.
· Must have same data type.
· Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.


What is "this" pointer?
Ans- The this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.
When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function. For example, the following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object's address is available from within the member function as the this pointer. It is legal, though unnecessary, to use the this pointer when referring to members of the class.

C/C++ Programming interview questions and answers

What is Memory alignment??
Ans- The term alignment primarily means the tendency of an address pointer value to be a multiple of some power of two. So a pointer with two byte alignment has a zero in the least significant bit. And a pointer with four byte alignment has a zero in both the two least significant bits. And so on. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.


What problem does the namespace feature solve?
Ans- Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.
namespace [identifier] { namespace-body }
A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.


What is the use of 'using' declaration?
Ans- A using declaration makes it possible to use a name from a namespace without the scope operator.


What is an Iterator class?
Ans- A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. Something like a pointer.


What is a dangling pointer?
Ans- A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

C/C++ Programming interview questions and answers

What is default constructor?
Ans- Constructor with no arguments or all the arguments has default values.


What is copy constructor?
Ans- Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Boo Obj1(10); // calling Boo constructor
Boo Obj2(Obj1); // calling boo copy constructor
Boo Obj2 = Obj1;// calling boo copy constructor


When are copy constructors called?
Ans- Copy constructors are called in following cases:
a) when a function returns an object of that class by value
b) when the object of that class is passed by value as an argument to a function
c) when you construct an object based on another object of the same class
d) When compiler generates a temporary object



What is assignment operator?
Ans- Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)



What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don't define one.??
Ans- default ctor
copy ctor
assignment operator
default destructor
address operator

C/C++ Programming interview questions and answers

What is encapsulation??

Ans- Containing and hiding information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object's operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data's origin.




What is inheritance?
Ans- Inheritance allows one class to reuse the state and behavior of another class. The derived class inherits the properties and method implementations of the base class and extends it by overriding methods and adding additional properties and methods.



What is Polymorphism??
Ans- Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
You can use implementation inheritance to achieve polymorphism in languages such as C++ and Java.
Base class object's pointer can invoke methods in derived class objects.
You can also achieve polymorphism in C++ by function overloading and operator overloading.



What is constructor or ctor?
Ans- Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.




What is destructor?
Ans- Destructor usually deletes any extra resources allocated by the object.
  • Blogger news

    This Blog Contains All Topics Related To Internet, Website Help, Interview Questions, News, Results From Various Resources, Visit Daily For More Interesting And Famous Topics.
  • Random Post

  • About

    We Provide All Information Which you Needed. We Maintain This Blog Very Carefully, If You Find Any Mistake or Any Suggestions Then Please Let Us Know, You Can Contact Us By Comments, On FB Page Or On Google+ Page. ~ Thank You