life ideas

November 6, 2007

C++ Questions

Filed under: Uncategorized — manoftoday @ 9:59 pm

1. type  size

#include <climits>

Base type  Minimum size (bits)  Minimum value (signed) Maximum value (signed)     Maximum value (unsigned)

char          8                                       -127(SCHAR_MIN)         127(SCHAR_MAX)                 255(UCHAR_MAX)

short int  16                                     -32,767(SHRT_MIN)       32,767(SHRT_MAX)              65,535(USHRT_MAX)

int             32                                     -2,147,483,647             2,147,483,647(INT_MAX)    4,294,967,295(UINT_MAX)

long         32                                      -2,147,483,647            2,147,483,647(LONG_MAX) 4,294,967,295(ULON_MAX)

If you might need large values (above 32,767 or below -32,767), use long. Otherwise, if space is very important (i.e. if there are large arrays or many structures), use short. Otherwise,use int.

2. difference between reference and pointer

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.

3. const

const function :  A member function can only be declared const if it doesn’t modify any of its fields(ie. this object).

const parameter;

const return value;

4. Micro vs inline function

the ordinary function do a lot of activity store the argument into stack,saving register control goes to the function and return value to the calling function ,but in inline function body replace to the calling the function (like as macro expansion). wherever the compiler finds the call for that function it puts the code for that function dere!! the functions are defined as inline when the function is small and is called many times.

it is reqest  to the compiler not a command,compiler may ignore the request if function is so length

5. name space

//Foo.hpp
namespace NS
{
  class Foo
  {
  public:
    void f();
    void g();
  };
}//close NS

//Foo.cpp
#include "Foo.hpp"
void NS::Foo::f()
{ /*..*/ }

void NS::Foo::g()
{ /*..*/ }

//Bar.hpp
namespace NS //Same Name space
{
  class Bar
  {
  public:
    void a();
  };
}
//Bar.cpp 
#include "Bar.hpp"
void NS::Bar::a()
{/*..*/}

void NS::Bar::b()
{/*..*/}
//main.cpp
#include "Bar.hpp"
#include "Foo.hpp"
int main()
{
  using NS::Bar; //a using declaration
  /* using namespace NS; // a using-directive  */
  Bar b;
  NS::Foo f;
  f.f();
  //...
}

6. How the compilers arranges the various sections in the executable image?

the compilers arranges the various sections in the executable image as following :

  • Data Section (uninitialized data variable section, initialized data variable section )
  • Code Section

Remember that all static variables are allocated in the initialized variable section.

7. C++ struct vs C++ class

This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, 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 specified and private base-class inheritance(it makes all of the public functions of the parent class private in the child class.).

8. malloc/free vs new/delete

Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.

9. When is a template a better solution than a base class?

When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.

10. default constructor, copy constructor, assignment operator

default constructor is required for Fred x[100]; or Fred abc; or Fred * p = new Fred[100];

class Fred {
public:

Fred(); // Default constructor: can be called with no args
Fred(int i=3, int j=5); // Default constructor: can be called with no args

};

You can NOT within one constructor of a class call another constructor of the same class to initialize. like :

Foo::Foo(char x)
{

Foo(x, 0); // this line does NOT help initialize the this object!!

}

but Java can accomplish this. solution is to have a init() routine that do the common work.

C++ implicitly declares a copy constructor and an assignment operator for every class, struct and union unless the user declared them explicitly.In C++, the implicitly declared assignment operator is a public and inline member function. C++ also guarantees member-wise assignment. The difference between member-wise copying and bitwise copying (such as a memcpy() call) is significant in two cases:

  • copying of subobjects (member-wise copying)

A shallow copy of an object copies all of the member field values. This works well if the fields are values, 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.

  • copying of padding bytes (bitwise copying)

A copy constructor will be called only when a new object is being instantiated. The assignment operator is called for an existing object to which a new value is being assigned.

Difference between copy constructor and assignment

  1. There is no need to test to see if it is being initialized from itself.
  2. There is no need to clean up (eg, delete) an existing value (there is none).
  3. A reference to itself is not returned.

When copy constructor is called?

  • A variable is declared which is initialized from another object, eg,
Person q("Mickey"); // constructor is used to build q.
Person r(q);        // copy constructor is used to build r.
Person p = q;       // copy constructor is used to initialize in declaration.
  • A value parameter is initialized from its corresponding argument.
    f(p);               // copy constructor initializes formal value parameter of function f(...)
  • An object is returned by a function.

Don’t write a copy constructor if shallow copies are ok

If the object has no pointers to dynamically allocated memory, a shallow copy is probably sufficient. Therefore the default copy constructor, default assignment operator, and default destructor are ok and you don’t need to write your own.

If you need a copy constructor, you also need a destructor and operator=

If you need a copy constructor, it’s because you need something like a deep copy, or some other management of resources. Thus is is almost certain that you will need a destructor and override the assignment operator.

A a;
A a2=a; //copy constructor call
A a3(a); //copy constructor call
a2=a3; //assignment operator for a2

As you can see, the fact that operator= is used doesn’t necessarily mean that the assignment operator is being called. The difference ere is semantic not syntactic — if the program is instantiating a new object, t’s the copy constructor call. If the object isn’t new, the ssignment expression translates into an assignment operator call.

Sample copy ctor and assignment operator

class Point {
public:
. . .
Point(const Point& p);   // copy constructor
. . .
//=== file Point.cpp ==========================================
. . .
Point::Point(const Point& p) {
x = p.x;
y = p.y;
}

class Person : public Parent
{
    private:
        char* _name;
        int   _id;
    public:
        Person& Person::operator=(const Person& p);
    . . .
}
//--- file Person.cpp
. . .
//=================================================== operator=
Person& Person::operator=(const Person& p) {
    if (this != &p) {  // (1)make sure not same object
        this->Parent::operator=(p);          // call base class's assignment 
        delete [] _name;                     // (2)Delete old name's memory.
        _name = new char[strlen(p._name)+1]; // (3)Get new space
        strcpy(_name, p._name);              // (4)Copy new name
        _id = p._id;                         // (4)Copy id
    }
    return *this;    // (5)Return ref for multiple assignment
}//end operator=

How to prevent object copying operation?

Declare the copy constructor and the assignment operator as private members, without defining them. Any statement that involves direct or indirect  copying of that class will cause a compilation error.

Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?

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.

11.  operator overloading

Prefix and Postfix

class Number {
public:
Number& operator++ ();
// prefix ++
Number operator++ (int);
// postfix ++ you must *not* make the postfix version return the ‘this’ object by reference;
};

Number& Number::operator++ ()    //Number abc(4); ++abc;
{

return *this;
}
Number Number::operator++ (int)

// Number abc(4); Number xyz = abc++; Number xyz2=abc.operator++(2); NOTE: xyz and xyz2 are the old value of abc
{
Number ans = *this;
++(*this);
// or just call operator++()
return ans;
}

The other option for the postfix version is to return nothing:

void Number::operator++ (int)
{
++(*this);
// or just call operator++()
}

subscriptor

When you have multiple subscripts, the cleanest way to do it is with operator() rather than with operator[]. The reason is that operator[] always takes exactly one parameter, but operator() can take any number of parameters (in the case of a rectangular matrix, two parameters are needed).

class Matrix {
public:
Matrix(unsigned rows, unsigned cols);
double& operator() (unsigned row, unsigned col);
subscript operators often come in pairs, m(5,8) = 106.15;
double operator() (unsigned row, unsigned col) const;
subscript operators often come in pairs,std::cout << m(5,8);

~Matrix();
// Destructor
Matrix(const Matrix& m);
// Copy constructor
Matrix& operator= (const Matrix& m);
// Assignment operator

private:
unsigned rows_, cols_;
double* data_;
};
inline
Matrix::Matrix(unsigned rows, unsigned cols)
: rows_ (rows)
, cols_ (cols)
//data_ <–initialized below (after the ‘if/throw’ statement)
{
if (rows == 0 || cols == 0)
throw BadIndex("Matrix constructor has 0 size");
data_ = new double[rows * cols];
}
inline
Matrix::~Matrix()
{
delete[] data_;
}
inline
double& Matrix::operator() (unsigned row, unsigned col)
{
if (row >= rows_ || col >= cols_)
throw BadIndex("Matrix subscript out of bounds");
return data_[cols_*row + col];
}
inline
double Matrix::operator() (unsigned row, unsigned col) const
{
if (row >= rows_ || col >= cols_)
throw BadIndex("const Matrix subscript out of bounds");
return data_[cols_*row + col];
}

stream overloading

Declare friend functions outside the public and private sections of the header file. Often they are placed first as in the example below.

//=== Point.h file =============================
class Point {
    friend ostream& operator<<(ostream& output, const Point& p);
    friend istream& operator>>(istream& input, Point& p);
    public:
        . . .
    private:
        . . .

ostream& operator<<(ostream& output, const Point& p) {
    output << "(" <<  p.x << ", " << p.y <<")";
    return output;  // for multiple << operators.
}

istream& operator>>(istream& input, Point& p){
      input >> p.x;
      input >> p.y
      return input ;
}
Binary operators
with the operator-assignments (like +=) ,which change the left-hand argument and return a reference
Integer& operator+=(Integer& left,const Integer& right) {
   if(&left == &right) {/* self-assignment */}
   left.i += right.i;
   return left;
}
Return by value as const(my note, not necessary to be perfect, non-constant is fine)
const Integer  operator+(const Integer& left, const Integer& right) {
  return Integer(left.i + right.i);
}

12. static key word

You may wonder why a global variable isn’t used instead. The beauty of a static variable is that it is unavailable outside the scope of the function, so it can’t be inadvertently changed. This localizes errors;

13. handle constructor and destructor fail

for constructor fail, throw an exception;

for destructor, The C++ rule is that you must never throw an exception from a destructor that is being called during the “stack unwinding” process of another exception. instead , Write a message to a log-file.

For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bar e)

So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you’re dead.

14. Exception

Generally, it’s best to throw objects, The most common practice is to throw a temporary:

#include <stdexcept>
class MyException : public std::runtime_error {
public:
MyException() : std::runtime_error(“MyException”) { }
};
void f()
{
// …
throw MyException();
}

Here, a temporary of type MyException is created and thrown. C++ allows you a variety of options for catching.

  • You can catch by value.
  • You can catch by reference.
  • You can catch by pointer.

Given all this flexibility, how do you decide what to catch? Simple: unless there’s a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer.

What does throw; (without an exception object after the throw keyword) mean? means “re-throw the current exception.”

try {

}
catch (MyException& e) {
e.addInfo(“f() failed”);
throw;
}

the advantage is that we can implement the re-throwing idiom as “exception dispatcher” in common place:

void handleException()
{
try {
throw;
}
catch (MyException& e) {
…code to handle MyException…
}
catch (YourException& e) {
…code to handle YourException…
}
}
void f()
{
try {
…something that might throw…
}
catch (…) {
handleException();
}
}

This idiom allows a single function (handleException()) to be re-used to handle exceptions in a number of other functions.

15. function pointer

http://www.newty.de/fpt/fpt.html

Many compilers have several calling conventions.you can precede __cdecl, __stdcall or __pascal to a function's type to indicate its calling convention (__cdecl is the default). C++ Builder also supports the __fastcall calling convention.


// calling convention,functions and function pointers with different calling convention are incompatible with each other!
void __cdecl DoIt(float a, char b, char c);                             // Borland and Microsoft
void DoIt(float a, char b, char c)  __attribute__((cdecl));     // GNU GCC

define a function pointer and initialize to NULL


int
(*pt2Function)(float, char, char) = NULL;                        // C
int (TMyClass::*pt2Member)(float, char, char) = NULL;                // C++
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;     // C++

or

  typedef int (*PT2FUNCTION)(float, char, char);
  PT2FUNCTION pt2Function = NULL;
  typedef int (TMyClass::*PT2MEMBER)(float, char, char);
  PT2MEMBER  pt2Member = NULL;



assign an address to the function pointer
//     Note: Although you may ommit the address operator on most compilers
//     you should always use the correct way in order to write portable code.

// C
int DoIt  (float a, char b, char c){ printf("DoIt\n");   return a+b+c; }
int DoMore(float a, char b, char c)const{ printf("DoMore\n"); return a-b+c; }

pt2Function = DoIt;      // short form
pt2Function = &DoMore;   // assignment using address operator looks better

// C++
class TMyClass
{
public:
   int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
   int DoMore(float a, char b, char c) const
         { cout << "TMyClass::DoMore" << endl; return a-b+c; };

   /* more of TMyClass */
};

pt2ConstMember = &TMyClass::DoMore; // assignment using address operator
pt2Member = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
invoke function pointer

// 2.5 calling a function using a function pointer
int result1 = pt2Function    (12, 'a', 'b');          // C short way
int result2 = (*pt2Function) (12, 'a', 'b');          // C

TMyClass instance1;
int result3 = (instance1.*pt2Member)(12, 'a', 'b');   // C++
int result4 = (*this.*pt2Member)(12, 'a', 'b');       // C++ if this-pointer can be used

TMyClass* instance2 = new TMyClass;
int result4 = (instance2->*pt2Member)(12, 'a', 'b');  // C++, instance2 is a pointer
delete instance2;

16. casting

A static_cast is used for all conversions that are well-defined. 
// Forcing a conversion from void* :
  void* vp = &i;
  // Old way produces a dangerous conversion:
  float* fp = (float*)vp;
  // The new way is equally dangerous:
  fp = static_cast<float*>(vp);
// well type cast
  double d = 0.0;
  int x = d; // Automatic type conversion
  x = static_cast<int>(d); // More explicit
If you want to convert from a const to a nonconst or from a volatile to a nonvolatile, you use const_cast.
A reinterpret_cast pretends that an object is just a bit pattern that can be treated (for some dark purpose)
as if it were an entirely different type of object.
A dynamic_cast is for type-safe downcasting
Shape * bp = new Circle();
Circle * cp = dynamic_cast<Circle*>(bp);

17. Array

Array Initialization

An array can be initialized in the declaration by writing a comma-separated list of values enclosed in braces following  an equal sign.

 int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

If the size is omitted, the compiler uses the number of values. For example,

int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};

  • If an array has no initialization, the values are undefined.
   float pressure[10];   // Initial values of pressure undefined.
  • Missing initialization values use zero, If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.
   float pressure[10] = {2.101, 2.32, 1.44};

Array pointer

   int abc[100];
   int *p = NULL;
   p = abc;
   p = &abc[0];
   abc == &abc == p != &p;

18. functor

There are several advantages in using a function object instead of a pointer to function.

  • First, they are more resilient to design changes because the object can be modified internally without changing its external interface.because if it is a pointer to function, the parameter is pre-fixed
  • A function object can also have data members that store the result of a previous call. when using ordinary functions, you need to store the result of a previous call in a global or a local static variable. However, global and local static variables have some undesirable characteristics.
  • Finally, compilers can inline a call made through a function object, thereby enhancing performance even further. In general, function objects do not define constructors and destructors. Therefore, they do not incur any overhead during their creation and destruction.

  class GenericNegate
  {
  public:
     template <class T>
     T operator() (T t) const {return -t;}
  };

  int main()
  {
   GenericNegate negate;
   cout<< negate<double>(5.3333); // double
   cout<< negate<__int64>(10000000000i64); // __int64
  }

19. Templates


/--- file generic/CheckedArray.h
#ifndef CHECKEDARRAY_H
#define CHECKEDARRAY_H

#include <stdexcept>

/////////////////////////////////// class CheckedArray<T>
template<class T>
class CheckedArray {
private:
    int size;  // maximum size
    T* a;      // pointer to new space
public:
    CheckedArray<T>(int max);
    ~CheckedArray<T>();
    T& CheckedArray<T>::operator[](int index);
};//end class CheckedArray<T>

//================================= constructor
template<class T>
CheckedArray<T>::CheckedArray<T>(int max) {
    size = max;
    a = new T[size];
}//end constructor
//================================= destructor
template<class T>
CheckedArray<T>::~CheckedArray<T>()
{
delete [] a;
}
//================================= operator[]
template<class T>
T& CheckedArray<T>::operator[](int index) {
    if (index < 0 || index >= size)
        throw out_of_range("CheckedArray");

    return a[index];
}//end operator[]
#endif

Partial Specializations and Explicit Specializations


template <class T> class Vector //primary template #1
{...};
template <class T> class Vector <T*> //partial specialization #2
{
....
void push_back(const T *p);
...
};
template <class T> class Vector <volatile T*> //partial specialization #3
{...};
template <> class Vector <bool> //explicit specialization #4
{};

Partial specialization
template<class T, class U, int I> struct X
  { void f() { cout << "Primary template" << endl; } };

template<class T, int I> struct X<T, T*, I> //note : no class U
  { void f() { cout << "Partial specialization 1" << endl;
  } };

template<class T, class U, int I> struct X<T*, U, I>
  { void f() { cout << "Partial specialization 2" << endl;
  } };

template<class T> struct X<int, T*, 10>
  { void f() { cout << "Partial specialization 3" << endl;
  } };

template<class T, class U, int I> struct X<T, U*, I>
  { void f() { cout << "Partial specialization 4" << endl;
  } };

20. Quick Answers

Polymorphism: C++ provides a simple mechanism for class-based polymorphism. Member  functions can be marked as polymorphic using the virtual keyword

The compiler starts with the Instrument pointer, which points to the starting address of the derived object. All Instrument objects or objects derived from Instrument have their VPTR in the same place (often at the beginning of the object), so the compiler can pick the VPTR out of the object. The VPTR points to the starting address of the VTABLE. All the VTABLEs are laid out in the same order, regardless of the specific type of the object. play( ) is first, what( ) is second, and adjust( ) is third. The compiler knows that regardless of the specific object type, the adjust( ) function is at the location VPTR+2. Thus instead of saying, “Call the function at the absolute location Instrument::adjust” (early binding; the wrong action), it generates code that says, in effect, “Call the function at VPTR+2.” Because the fetching of the VPTR and the determination of the actual function address occur at runtime, you get the desired late binding. You send a message to the object, and the object figures out what to do with it.

http://web.mit.edu/merolish/ticpp/Chapter15.html#Heading440

why constructor can’t be virtual?2.


A constructor cannot be virtual because at the time when the constructor is invoked the virtual table (vtable) would not be available in the memory. Hence we cannot have a virtual constructor.

The ‘virtual’ mechanism works on a logically complete (completely constructed) object. We know that we use constructors to logically initialize our objects. In other words, the object is not completely constructed until the constructor has finished executing. Thus, we can’t have virtual constructors.

There is a misconception that by then virtual table is incomplete so we can’t have virtual constructors. Just before the constructor starts executing : 1)the virtual table is properly constructed and 2)the ‘this’ pointer passed to the constructors. Moreover, virtual table mechanism is implementation depended, and finds no place in the C++ standard. And hence, to argue over this issue using the virtual table concept is illogical.

Now, as the constructor finishes executing any other function can be virtual. Destructor is no exception to this rule as it is a function. Virtual destructors are required in case we use a base class pointer to refer to a derived class object, use it, and then delete it. If we have virtual destructor, using ‘delete’, a chain of destructors is called starting from the derived to the base. But, had there been no ‘virtual’ in destructor only the base class destructor is called (and not the derived). This (may) generate inconsistencies in the program.


How virtual functions are implemented C++?

Virtual functions are implemented using a table of function pointers, called the vtable.  There is one entry in the table per virtual function in the class.  This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions


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.??

default ctor

default destructor

copy ctor

assignment operator

address operator

diff of static vs global

there are 3 main uses for the static.
1. If you declare within a function: It retains the value between function calls

2.If it is declared for a function name:
By default function is extern.so it will be visible from other files.  if the function declaration is as static.it is invisible for the outer files

3. Static for global variables:

By default we can use the global variables from outside files If it is static global..that variable is limitied to with in the file.

common:  lifetime is the entire program….

What are C++ storage classes?

auto(deafult)
register
static
extern

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. They are not visible outside that block

register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance

static: a variable that is known only in 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

extern: a variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.

What are storage qualifiers in C++ ?

They are..

const
volatile
mutable

Const keyword indicates that memory once initialized, should not be altered by a program.

volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.

mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

struct data
{
char name[80];
mutable double salary;
}

const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier

strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

What is Memory alignment??

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 do you mean by Stack unwinding?

It is a process during exception handling when the destructor is called for all local objects in the stack between the place where the exception was thrown and where it is caught.

What is overloading??

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?

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.

How are prefix and postfix versions of operator++() differentiated?

The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter.

What is the difference between const char *myPointer and char *const myPointer?

Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.

What is name mangling in C++??

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 does extern “C” int func(int *, Foo) accomplish?

It will turn off “name mangling” for func in c++ so that one can link to code of func implementation compiled by a C compiler.

What are the access privileges in C++? What is the default access level?

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?

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?

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.

What is the difference between a variable definition and a variable declaration?

A definition tells the compiler to set aside storage for the variable. A declaration makes the variable known to parts of the program that may wish to use it. A variable might be defined and declared in the same statement.

What is the difference between an lvalue and an rvalue?

The lvalue refers to the left-hand side of an assignment expression. It must always evaluate to a memory location. The rvalue represents the right-hand side of an assignment expression; it may have any meaningful combination of variables and constants.

How to make sure all objects created in a function be destroyed (?)(C++)

overload new/delete;

check-memory usage enter/exit func;

auto_ptr;

Note that our detector detects leaks without doing any monitoring of allocations or frees. It simply takes a snapshot of the heap just before the process terminates and determines if there are any leaks based on that snapshot. A snapshot of the heap only tells us if there are leaks; it does not tell us how they were leaked. Clearly, to determine the “how” we also need to obtain a stack trace. But to obtain a stack trace, we need to be able to monitor every allocation on-the-fly at runtime. This is what will distinguish our leak detector from the built-in one.

How to implement smart pointer

A common pitfall of regular pointers is the dangling pointer: a pointer that points to an object that is already deleted.

Here is part of auto_ptr’s implementation, to illustrate what it does:

template <class T>
class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;ptr=NULL}
    T& operator*()              {return *ptr;}
    T* operator->()             {return ptr;}
    // ...
};

http://ootips.org/yonat/4dev/smart-pointers.html

why initialization list is listed?

(1)According to the rules of C++, const objects and references cannot be assigned; they can only be initialized

(2)The second reason for using the initializer list—efficiency—arises when the member class has a default constructor as well as an assignment operator. MFC’s CString offers a perfect example. Say you have a class CMyClass with a CString member m_str and you want to initialize m_str to “yada yada.” You have two choices

CMyClass::CMyClass() {
    // use assignment operator
    // CString::operator=(LPCTSTR);
    m_str = _T("yada yada");
}

or

// use initializer list
// and constructor CString::CString(LPCTSTR)
CMyClass::CMyClass() : m_str(_T("yada yada"))
{
}

Is there any difference between these methods? Yes. The compiler always insures that all member objects are initialized before the body of the constructor executes, so in the first example the compiled code will call CString::CString to initialize m_str before control reaches the assignment statement. In the second example, the compiler generates a call to CString:: CString(LPCTSTR), passing “yada yada” as the string. The upshot is that in the first example two CString functions are called (constructor and assignment operator), whereas in the second example only one function is called.

dead lock sample, how to avoid

  public static Object cacheLock = new Object();
  public static Object tableLock = new Object();
  ...
  public void oneMethod() {
    synchronized (cacheLock) {
      synchronized (tableLock) {
        doSomething();
      }
    }
  }
  public void anotherMethod() {
    synchronized (tableLock) {
      synchronized (cacheLock) {
        doSomethingElse();
      }
    }
  }

that thread A acquires the lock on cacheLock, and, at the same time, thread B acquires the lock on tableLock. Now the threads are deadlocked: neither thread will give up its lock until it acquires the other lock, but neither will be able to acquire the other lock until the other thread gives it up.

How to avoid deadlocks

http://www.javaworld.com/javaworld/jw-10-2001/jw-1012-deadlock.html?page=3

One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time, which is often practical. for instance, Shrink synchronized blocks to avoid multiple locking;

otherwise, ensure that you use a consistent locking order. or enforce business logic to avoid deadlock happen.

How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.

http://vijayinterviewquestions.blogspot.com/2007/05/how-would-you-detect-loop-in-linked.html

This is also one of the classic interview questions
There are multiple answers to this problem. Here are a few C programs to attack this problem.

Brute force method
Have a double loop, where you check the node pointed to by the outer loop, with every node of the inner loop.

typedef struct node

{

void *data;

struct node *next;

}mynode;

mynode * find_loop(NODE * head)

{

mynode *current = head;

while(current->next != NULL)

{

mynode *temp = head;

while(temp->next != NULL && temp != current)

{

if(current->next == temp)

{

printf(“\nFound a loop.”);

return current;

}

temp = temp->next;

}

current = current->next;

}

return NULL;

}

Visited flag
Have a visited flag in each node of the linked list. Flag it as visited when you reach the node. When you reach a node and the flag is already flagged as visited, then you know there is a loop in the linked list.

Fastest method
Have 2 pointers to start of the linked list. Increment one pointer by 1 node and the other by 2 nodes. If there’s a loop, the 2nd pointer will meet the 1st pointer somewhere. If it does, then you know there’s one.

Here is some code
p=head;

q=head->next;
while(p!=NULL && q!=NULL)

{

if(p==q) { //Loop detected! exit(0); }

p=p->next;

q=(q->next)?(q->next->next):q->next;

}
// No loop.

What is the difference between far pointer and nea…


In 16 bit development environment like DOS or WIN 3.0 memory management is done in terms of segment:offset addressing style. so in this environment we have segment registers like CS,DS.SS,ES if we declare a near pointer we will be able to access the pointer within the segment i.e with 64 kb boundary

on the contrary if we declare it as far pointer we can access the pointer across segment boundary i.e pointer declared in one segment can be accessed from other segments also.
In 32 bit environment we have linear addressing scheme no segments and offsets so all pointers are treated as far only, no differentiation as near or far.

Why an empty Structure will occupy 2Bytes in C++


Size of empty structure in C++ is 1 byte, because compiler assign 1 byte for structure name.

Why the size of empty Class is one byte?


Yes, the compiler will generate 1 byte of memory to mark the existence of the class.  This doesn’t answer WHY though.  The reason is the language standard states that all classes must have a memory size of at least 1 byte so that the class doesn’t occupy the same memory space with another class. This is to prevent name mangling.  i.e., if I declare a class A {};, the compiler will still generate an entry in its table to something called “A”.  If behind that I declare another class, say class B, if A takes 0 bytes of memory, and B’s data gets written in the place where A was declared.  In this case, an instantiation of A would take on the properties of B.

What is difference between obeject oriented progra…


Object Oriented Programming :  It means, which follows object oriented concepts that is object oriented programming for example : c++, java and also c++ is not complete objected oriented. But java is pure objected oriented programming.
object oriented programming is bottom up approach.
program works based on object.
object is nothing set of members and methods.
Structure Oriented Programming : it means, which follows and structure ( function ) oriented concepts, a program which follows a procedure ( or a structure ) is called structure oriented programming for example : c lang
Structure Oriented Programming is top down approach.

program works based on functions.

what are proxy objectives


A proxy class is a class that implements a list of interfaces specified at compile time. The proxy object typically holds a reference to an internal object that implements the same interfaces (or parts of them).

Rational Purify, sleaker,valgrind,Electric Fence

Ref:

http://www.fredosaurus.com/notes-cpp/index.html

http://www.freejavaguide.com/cppint.htm

http://www.shettysoft.com/interview/C_C++_interview_questions_answers.htm

http://www.coders2020.com/c-faq-for-placement-and-interviews

http://c-faq.com/decl/

Advertisements

Create a free website or blog at WordPress.com.