C, C++ Interview Questions

Q : What is a heap ?
Ans : Heap is a chunk of memory. When in a program memory is allocated dynamically, the C run-time library gets the memory from a collection of unused memory called the heap. The heap resides in a program's data segment. Therefore, the amount of heap space available to the program is fixed, and can vary from one program to another.

Q : How to obtain a path of the given file?
Ans: The function searchpath( ) searches for the specified file in the subdirectories of the current path. Following program shows how to make use of the searchpath( ) function.

#include "dir.h"

void main ( int argc, char *argv[] )
{
char *path ;
if ( path = searchpath ( argv[ 1 ] ) )
printf ( "Pathname : %s\n", path ) ;
else
printf ( "File not found\n" ) ;
}

Q : Can we get the process identification number of the current program?
Ans: Yes! The macro getpid( ) gives us the process identification number of the program currently running. The process id. uniquely identifies a program. Under DOS, the getpid( ) returns the Program Segment Prefix as the process id. Following program illustrates the use of this macro.
#include
#include

void main( )
{
printf ( "The process identification number of this program is %X\n",
getpid( ) ) ;
}

Q : How do I write a function that takes variable number of arguments?
Ans: The following program demonstrates this.

#include
#include

void main( )
{
int i = 10 ;
float f = 2.5 ;
char *str = "Hello!" ;
vfpf ( "%d %f %s\n", i, f, str ) ;
vfpf ( "%s %s", str, "Hi!" ) ;
}

void vfpf ( char *fmt, ... )
{
va_list argptr ;
va_start ( argptr, fmt ) ;
vfprintf ( stdout, fmt, argptr ) ;
va_end ( argptr ) ;
}

Here, the function vfpf( ) has called vfprintf( ) that take variable argument lists. va_list is an array that holds information required for the macros va_start and va_end. The macros va_start and va_end provide a portable way to access the variable argument lists. va_start would set up a pointer argptr to point to the first of the variable arguments being passed to the function. The macro va_end helps the called function to perform a normal return.

Q : Can we change the system date to some other date?
Ans: Yes, We can! The function stime( ) sets the system date to the specified date. It also sets the system time. The time and date is measured in seconds from the 00:00:00 GMT, January 1, 1970. The following program shows how to use this function.
#include
#include

void main( )
{
time_t tm ;
int d ;

tm = time ( NULL ) ;

printf ( "The System Date : %s", ctime ( &tm ) ) ;
printf ( "\nHow many days ahead you want to set the date : " ) ;
scanf ( "%d", &d ) ;

tm += ( 24L * d ) * 60L * 60L ;

stime ( &tm ) ;
printf ( "\nNow the new date is : %s", ctime ( &tm ) ) ;
}
In this program we have used function ctime( ) in addition to function stime( ). The ctime( ) function converts time value to a 26-character long string that contains date and time.

Q : How to use function strdup( ) in a program?
Ans : The string function strdup( ) copies the given string to a new location. The function uses malloc( ) function to allocate space required for the duplicated string. It takes one argument a pointer to the string to be duplicated. The total number of characters present in the given string plus one bytes get allocated for the new string. As this function uses malloc( ) to allocate memory, it is the programmer’s responsibility to deallocate the memory using free( ).
#include
#include
#include

void main( )
{
char *str1, *str2 = "double";

str1 = strdup ( str2 ) ;
printf ( "%s\n", str1 ) ;
free ( str1 ) ;
}

Q : On including a file twice I get errors reporting redefinition of function.
How can I avoid duplicate inclusion?
Ans: Redefinition errors can be avoided by using the following macro definition. Include this definition in the header file.
#if !defined filename_h
#define filename_h
/* function definitions */
#endif
Replace filename_h with the actual header file name. For example, if name of file to be included is 'goto.h' then replace filename_h

Q : How to write a swap( ) function which swaps the values of the variables using bitwise operators.

Ans: Here is the swap( ) function.
swap ( int *x, int *y )
{
*x ^= *y ;
*y ^= *x ;
*x ^= *y ;
}
The swap( ) function uses the bitwise XOR operator and does not require any temporary variable for swapping.

C++ Interview Questions

Q. Name some pure object oriented languages.
Answer:

 Smalltalk,
 Java,
 Eiffel,
 Sather.

Q. Name the operators that cannot be overloaded.
Answer:
sizeof . .* .-> :: ?:

Q. What is a node class?
Answer:

A node class is a class that,
 relies on the base class for services and implementation,
 provides a wider interface to te users than its base class,
 relies primarily on virtual functions in its public interface
 depends on all its direct and indirect base class
 can be understood only in the context of the base class
 can be used as base for further derivation
 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.

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

Q. What is a container class? What are the types of container classes?
Answer: 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.

Q. What is a protocol class?
Answer: An abstract class is a protocol class if:

 it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
 it has a non-inline virtual destructor defined with an empty implementation,
 all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

Q. What is a mixin class?
Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

Q. What is a concrete class?
Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

Q.What is the handle class?
Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.

Explanation:

In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.

A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.

Q. What is an action class?
Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.

Explanation:
A common form of action class is a simple class containing just one virtual function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

C++ Interview Questions

Q. Name some pure object oriented languages.
Answer:

 Smalltalk,
 Java,
 Eiffel,
 Sather.

Q. Name the operators that cannot be overloaded.
Answer:
sizeof . .* .-> :: ?:

Q. What is a node class?
Answer:

A node class is a class that,
 relies on the base class for services and implementation,
 provides a wider interface to te users than its base class,
 relies primarily on virtual functions in its public interface
 depends on all its direct and indirect base class
 can be understood only in the context of the base class
 can be used as base for further derivation
 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.

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

Q. What is a container class? What are the types of container classes?
Answer: 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.

Q. What is a protocol class?
Answer: An abstract class is a protocol class if:

 it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
 it has a non-inline virtual destructor defined with an empty implementation,
 all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

Q. What is a mixin class?
Answer: A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

Q. What is a concrete class?
Answer: A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

Q.What is the handle class?
Answer: A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.

Explanation:

In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.

A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.

Q. What is an action class?
Answer: The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.

Explanation:
A common form of action class is a simple class containing just one virtual function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

C++ Interview Questions

Q. What is an incomplete type?
Answer: Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification.
Example:
int *i=0x400 // i points to address 400
*i=0; //set the value of memory location pointed by i.
Incomplete types are otherwise called uninitialized pointers.

Q. What is a dangling pointer?
Answer: 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.

Q. Differentiate between the message and method.
Answer:

Message Method
Objects communicate by sending messages Provides response to a message.
to each other.
A message is sent to invoke a method. It is an implementation of an operation.

Q. What is an adaptor class or Wrapper class?
Answer: A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation.

Q. What is a Null object?
Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

Q. What is a Null object?
Answer: It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

Q. What is class invariant?
Answer: A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

Q. What do you mean by Stack unwinding?
Answer: It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

Q. Define precondition and post-condition to a member function.
Answer:

Precondition: A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.

Post-condition: A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

Q. What are the conditions that have to be met for a condition to be an invariant of the class?
Answer:

 The condition should hold at the end of every constructor.
 The condition should hold at the end of every mutator(non-const) operation.

Q. What are proxy objects?
Answer:

Objects that stand for other objects are called proxy objects or surrogates.

Example:
template
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index) const;
...
};
Array1D operator[] (int index);
const Array1D operator[] (int index) const;
...
};

The following then becomes legal:
Array2Ddata(10,20);
........

C++ Interview Questions

Q. What is a modifier?
Answer: A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’.

Q. What is an accessor?
Answer: An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

Q. Differentiate between a template class and class template.
Answer:

Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.

Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

Q. When does a name clash occur?
Answer: A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.

Q. Define namespace.
Answer: It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

Q. What is the use of ‘using’ declaration.
Answer: A using declaration makes it possible to use a name from a namespace without the scope operator.

Q. What is an Iterator class?
Answer: 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.
The simplest and safest iterators are those that permit read-only access to the contents of a container class. The following code fragment shows how an iterator might appear in code:
cont_iter:=new cont_iterator();
x:=cont_iter.next();
while x/=none do
...
s(x);
...
x:=cont_iter.next();
end;
In this example, cont_iter is the name of the iterator. It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x. The loop terminates when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on x, the current element from the container. The next element of the container is obtained at the bottom of the loop.

Q. List out some of the OODBMS available.
Answer:

 GEMSTONE/OPAL of Gemstone systems.
 ONTOS of Ontos.
 Objectivity of Objectivity inc.
 Versant of Versant object technology.
 Object store of Object Design.
 ARDENT of ARDENT software.
 POET of POET software.

Q. List out some of the object-oriented methodologies.
Answer:

 Object Oriented Development (OOD) (Booch 1991,1994).
 Object Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991).
 Object Modelling Techniques (OMT) (Rumbaugh 1991).
 Object Oriented Software Engineering (Objectory) (Jacobson 1992).
 Object Oriented Analysis (OOA) (Shlaer and Mellor 1992).
 The Fusion Method (Coleman 1991).

C++ Interview Questions

Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?
A: There is nothing like Virtual Constructor. The constructor can’t be virtual as the constructor is a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

Q: What is Constructor ?
A: Constructor creates an object and initializes it. It also creates V-Table for virtual functions. It is different from other methods in a class.

Q: What about Virtual Destructor?
A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object caller is calling to, proper destructor will be called.
Q: What is the difference between a copy constructor and an overloaded assignment operator?
A: A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?
A: The constructor never throws an error.

Q: What is default constructor?
A: Constructor with no arguments or all the arguments has default values.

Q: What is default (Implicit) copy constructor?
A: Constructor which initializes 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.
Examples:
(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor

Q: When is copy constructors called?
A: 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

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
A: 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.

Q: What is conversion constructor?
A: constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.

Example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object

Q:What is conversion operator??
A:class can have a public method for specific data type conversions.

For example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};

Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.

Q: How can I handle a constructor that fails?
A: 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.

Q: How can I handle a destructor that fails?
A: Write a message to a log-_le. But do not throw an exception. 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. 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 (Bare) { handler? There is no good answer:either choice loses information. So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.

Q: What is Virtual Destructor?
A: Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes. if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?
A: 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.

Q: What's the order that local objects are destructed?
A: In reverse order of construction: First constructed, last destructed. In the following example, b's destructor will be executed first, then a's destructor:
void userCode()
{
Fred a;
Fred b;
...
}

Q: What's the order that objects in an array are destructed?
A: In reverse order of construction: First constructed, last destructed. In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}

C++ portability rules

Labels: , | 0 comments

12. Don't put extra top-level semi-colons in code.

Non-portable example:

int
A::foo()
{
};

This is another problem that seems to show up more on C++ than C code. This problem is really a bit of a drag. That extra little semi-colon at the end of the function is ignored by most compilers, but it is not permitted by the standard and it makes some compilers report errors (in particular, gcc 3.4, and also perhaps old versions of the AIX native compiler). Don't do it.
Portable example:

int
A::foo()
{
}

13. C++ filename extension is .cpp.

This one is another plain annoying problem. What's the name of a C++ file? file.cpp, file.cc, file.C, file.cxx, file.c++, file.C++? Most compilers could care less, but some are very particular. We have not been able to find one file extension which we can use on all the platforms we have ported Mozilla code to. For no great reason, we've settled on file.cpp, probably because the first C++ code in Mozilla code was checked in with that extension. Well, it's done. The extension we use is .cpp. This extension seems to make most compilers happy, but there are some which do not like it. On those systems we have to create a wrapper for the compiler (see STRICT_CPLUSPLUS_SUFFIX in ns/config/rules.mk and ns/build/*), which actually copies the file.cpp file to another file with the correct extension, compiles the new file, then deletes it. If in porting to a new system, you have to do something like this, make sure you use the #line directive so that the compiler generates debug information relative to the original .cpp file.

14. Don't mix varargs and inlines.

Non-portable example:

class FooBar {
void va_inline(char* p, ...) {
// something
}
};

The subject says it all, varargs and inline functions do not seem to mix very well. If you must use varargs (which can cause portability problems on their own), then ensure that the vararg member function is a non-inline function.
Portable example:

// foobar.h
class FooBar {
void
va_non_inline(char* p, ...);
};

// foobar.cpp
void
FooBar::va_non_inline(char* p, ...)
{
// something
}

15. Don't use initializer lists with objects.

Non-portable example:

FooClass myFoo = {10, 20};

Some compilers won't allow this syntax for objects (HP-UX won't), actually only some will allow it. So don't do it. Again, use a wrapper function, see Don't use static constructors.
Always have a default constructor.

Always have a default constructor, even if it doesn't make sense in terms of the object structure/hierarchy. HP-UX will barf on statically initialized objects that don't have default constructors.

C++ portability rules

Labels: , | 0 comments

6. Don't use namespace facility.


Support of namespaces (through the namespace and using keywords) is a relatively new C++ feature, and not supported in many compilers. Don't use it.


7. main() must be in a C++ file.


The first C++ compiler, Cfront, was in fact a very fancy preprocessor for a C compiler. Cfront reads the C++ code, and generates C code that would do the same thing. C++ and C startup sequences are different (for example static constructor functions must be called for C++), and Cfront implements this special startup by noticing the function called "main()", converting it to something else (like "__cpp__main()"), adding another main() that does the special C++ startup things and then calls the original function. Of course for all this to work, Cfront needs to see the main() function, hence main() must be in a C++ file. Most compilers lifted this restriction years ago, and deal with the C++ special initialization duties as a linker issue. But there are a few commercial compilers shipping that are still based on Cfront: HP, and SCO, are examples.


So the workaround is quite simple. Make sure that main() is in a C++ file. On the Unix version of Mozilla, we did this by adding a new C++ file which has only a few lines of code, and calls the main main() which is actually in a C file.


8. Use the common denominator between members of a C/C++ compiler family.


For many of the compiler families we use, the implementation of the C and C++ compilers are completely different, sometimes this means that there are things you can do in the C language, that you cannot do in the C++ language on the same machine. One example is the 'long long' type. On some systems (IBM's compiler used to be one, but I think it's better now), the C compiler supports long long, while the C++ compiler does not. This can make porting a pain, as often times these types are in header files shared between C and C++ files. The only thing you can do is to go with the common denominator that both compilers support. In the special case of long long, we developed a set of macros for supporting 64 bit integers when the long long type is not available. We have to use these macros if either the C or the C++ compiler does not support the special 64 bit type.


9. Don't put C++ comments in C code.


The quickest way to raise the blood pressure of a Netscape Unix engineer is to put C++ comments (// comments) into C files. Yes, this might work on your Microsoft Visual C compiler, but it's wrong, and is not supported by the vast majority of C compilers in the world. Just do not go there.


Many header files will be included by C files and included by C++ files. We think it's a good idea to apply this same rule to those headers. Don't put C++ comments in header files included in C files. You might argue that you could use C++ style comments inside #ifdef __cplusplus blocks, but we are not convinced that is always going to work (some compilers have weird interactions between comment stripping and pre-processing), and it hardly seems worth the effort. Just stick to C style /**/ comments for any header file that is ever likely to be included by a C file.


10. Don't put carriage returns in XP code.


While this is not specific to C++, we have seen this as more of an issue with C++ compilers, see Use the common denominator between members of a C/C++ compiler family. In particular, it causes bustage on at least the IRIX native compiler.


On unix systems, the standard end of line character is line feed ('\n'). The standard on many PC editors is carriage return and line feed ("\r\n"), while the standard on Mac is carriage return ("\r"). The PC compilers seem to be happy either way, but some Unix compilers just choke when they see a carriage return (they do not recognize the character as white space). So, we have a rule that you cannot check in carriage returns into any cross platform code. This rule is not enforced on the Windows front end code, as that code is only ever compiled on a PC. The Mac compilers seem to be happy either way, but the same rule applies as for the PC - no carriage returns in cross platform code.


MacCVS, WinCVS, and cygwin CVS when configured to use DOS line endings automatically convert to and from platform line endings, so you don't need to worry. However, if you use cygwin CVS configured for Unix line endings, or command line cvs on Mac OS X, you need to be somewhat careful.


11. Put a new line at end-of-file.


Not having a new-line char at the end of file breaks .h files with the Sun WorkShop compiler and it breaks .cpp files on HP.

C++ portability rules

Labels: , | 0 comments

1. Be very careful when writing C++ templates.

Don't use C++ templates unless you do only things already known to be portable because they are already used in Mozilla (such as patterns used by nsCOMPtr or CallQueryInterface) or are willing to test your code carefully on all of the compilers we support and be willing to back it out if it breaks.

2. Don't use static constructors.

Non-portable example:

FooBarClass static_object(87, 92);

void
bar()
{
if (static_object.count > 15) {
...
}
}

Static constructors don't work reliably either. A static initialized object is an object which is instanciated at startup time (just before main() is called). Usually there are two components to these objects. First there is the data segment which is static data loaded into the global data segment of the program. The second part is a initializer function that is called by the loader before main() is called. We've found that many compilers do not reliably implement the initializer function. So you get the object data, but it is never initialized. One workaround for this limitation is to write a wrapper function that creates a single instance of an object, and replace all references to the static initialized object with a call to the wrapper function:
Portable example:

static FooBarClass* static_object;

FooBarClass*
getStaticObject()
{
if (!static_object)
static_object =
new FooBarClass(87, 92);
return static_object;
}

void
bar()
{
if (getStaticObject()->count > 15) {
...
}
}

3. Don't use exceptions.

Exceptions are another C++ feature which is not very widely implemented, and as such, their use is not portable C++ code. Don't use them. Unfortunately, there is no good workaround that produces similar functionality.

One exception to this rule (don't say it) is that it's probably ok, and may be necessary to use exceptions in some machine specific code. If you do use exceptions in machine specific code you must catch all exceptions there because you can't throw the exception across XP (cross platform) code.

4. Don't use Run-time Type Information.

Run-time type information (RTTI) is a relatively new C++ feature, and not supported in many compilers. Don't use it.

If you need runtime typing, you can achieve a similar result by adding a classOf() virtual member function to the base class of your hierarchy and overriding that member function in each subclass. If classOf() returns a unique value for each class in the hierarchy, you'll be able to do type comparisons at runtime.

5. Don't use C++ standard library features, including iostream

Using C++ standard library features involves significant portability problems because newer compilers require the use of namespaces and of headers without .h, whereas older compilers require the opposite. This includes iostream features, such as cin and cout.

Furthermore, using the C++ standard library imposes difficulties on those attempting to use Mozilla on small devices.

There is one exception to this rule: it is acceptable to use placement new. To use it, include the standard header by writing #include NEW_H.

C optimisations

Labels: , | 0 comments

Loop jamming

Never use two loops where one will suffice:
for(i=0; i<100; i++)
{
stuff();
}

for(i=0; i<100; i++)
{
morestuff();
}
It would be better to do:
for(i=0; i<100; i++)
{
stuff();
morestuff();
}
Note, however, that if you do a lot of work in the loop, it might not fit into your processor's instruction cache. In this case, two separate loops may actually be faster as each one can run completely in the cache.

--------------------------------------------------------------------------------

Faster for() loops

Simple but effective.
Ordinarily, you would code a simple for() loop like this:
for( i=0; i<10; i++){ ... }
i loops through the values 0,1,2,3,4,5,6,7,8,9
If you don't care about the order of the loop counter, you can do this instead:

for( i=10; i--; ) { ... }
Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be faster.
This works because it is quicker to process "i--" as the test condition, which says "is i non-zero? If so, decrement it and continue.".
For the original code, the processor has to calculate "subtract i from 10. Is the result non-zero? if so, increment i and continue.". In tight loops, this make a considerable difference.
The syntax is a little strange, put is perfectly legal. The third statement in the loop is optional (an infinite loop would be written as "for( ; ; )" ). The same effect could also be gained by coding:

for(i=10; i; i--){}
or (to expand it further)
for(i=10; i!=0; i--){}
The only things you have to be careful of are remembering that the loop stops at 0 (so if you wanted to loop from 50-80, this wouldn't work), and the loop counter goes backwards.It's easy to get caught out if your code relies on an ascending loop counter.

--------------------------------------------------------------------------------

switch() instead of if...else...

For large decisions involving if...else...else..., like this:
if( val == 1)
dostuff1();
else if (val == 2)
dostuff2();
else if (val == 3)
dostuff3();
it may be faster to use a switch:
switch( val )
{
case 1: dostuff1(); break;

case 2: dostuff2(); break;

case 3: dostuff3(); break;
}
In the if() statement, if the last case is required, all the previous ones will be tested first. The switch lets us cut out this extra work. If you have to use a big if..else.. statement, test the most likely cases first.

C optimisations

Using array indices

If you wished to set a variable to a particular character, depending upon the value of something, you might do this :

switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
or maybe
if ( queue == 0 )
letter = 'W';
else if ( queue == 1 )
letter = 'S';
else
letter = 'U';
A neater ( and quicker ) method is to simply use the value as an index into a character array, eg.
static char *classes="WSU";

letter = classes[queue];
--------------------------------------------------------------------------------
Aliases

Consider the following:
void func1( int *data )
{
int i;

for(i=0; i<10;>
{
somefunc2( *data, i);
}
}
Even though "*data" may never change, the compiler does not know that somefunc2() did not alter it, and so the program must read it from memory each time it is used - it may be an alias for some other variable that is altered elsewhere. If you know it won't be altered, you could code it like this instead:
void func1( int *data )
{
int i;
int localdata;

localdata = *data;
for(i=0; i<10;>
{
somefunc2( localdata, i);
}
}
This gives the compiler better opportunity for optimisation.

--------------------------------------------------------------------------------

Integers

Use unsigned ints instead of ints if you know the value will never be negative. Some processors can handle unsigned integer arithmetic considerably faster than signed ( this is also good practise, and helps make for self-documenting code).
So the best declaration for an int variable in a tight loop would be

register unsigned int var_name;

(although it is not guaranteed that the compiler will take any notice of "register", and "unsigned" may make no difference to the processor.)

Remember, integer arithmetic is much faster than floating-point arithmetic, as it can be usually be done directly by the processor, rather than relying on external FPUs or floating point maths libraries. If you only need to be accurate to two decimal places (e.g. in a simple accounting package), scale everything up by 100, and convert it back to floating point as late as possible.

C++ Optimizations

Avoid Expensive Operations
Addition is cheaper than multiplication and multiplication is cheaper than division. Factor out expensive operations whereever possible.

Initialize on Declaration
Whereever possible, initialize variables at the time they're declared. For example,

TMyClass myClass = data;

is faster than

TMyClass myClass;
myClass = data;

Declaration then initialization invokes the object's default constructor then its assignment operator. Initializing in the declaration invokes only its copy constructor.

Pass By Reference
Always try to pass classes by reference rather than by value. For example, use

void foo(TMyClass &myClass)

rather than

void foo(TMyClass myClass)

Delay Variable Declarations
Leave variable declarations right until the point when they're needed. Remember that when a variable is declared its constructor is called. This is wasteful if the variable is not used in the current scope.

Use 'op='
Wherever possible, use 'op=' in favour of 'op'. For example, use

myClass += value;

rather than

myClass = myClass + value;

The first version is better than the second because it avoids creating a temporary object.

Inline Small Functions
Small, performance critical functions should be inlined using the inline keyword, e.g.,

inline void foo()

This causes the compiler to duplicate the body of the function in the place it was called from. Inlining large functions can cause cache misses resulting in slower execution times.

Use Nameless Classes
Whereever possible, use nameless classes. For example,

foo(TMyClass("abc"));

is faster than

TMyClass myClass("abc");
foo(myClass);

because, in the first case, the parameter and the class share memory.

C++ Optimizations

These optimizations are fairly easy to apply to existing code and in some cases can result in big speedups. Remember the all-important maxim though, the fastest code is code that isn't called.

Use Initialization Lists
Always use initialization lists in constructors. For example, use

TMyClass::TMyClass(const TData &data) : m_Data(data)
{
}

rather than

TMyClass::TMyClass(const TData &data)
{
m_Data = data;
}

Without initialization lists, the variable's default constructor is invoked behind-the-scenes prior to the class's constructor, then its assignment operator is invoked. With initialization lists, only the copy constructor is invoked.

Optimize For Loops
Whereever possible, count down to zero rather than up to n. For example, use

for (i = n-1; i >= 0; --i)

rather than

for (i = 0; i <>

The test is done every iteration and it's faster to test against zero than anything else. Note also that

++i

is faster than

i++

when it appears in the third part of the for loop statement.

Use 'int'
Always use the int data type instead of char or short wherever possible. int is always the native type for the machine.

Make Local Functions Static
Always declare local functions as static, e.g.,

static void foo()

This means they will not be visible to functions outside the .cpp file, and some C++ compilers can take advantage of this in their optimizations.

Optimize If Statements
Factor out jumps. For example, use

bar();
if (condition)
{
undoBar();
foo();
}
rather than

if (condition)
{
foo();
}
else
{
bar();
}

Use a profiler and good judgement to decide if undoing the bar() operation is faster than jumping.

Optimize Switch Statements
Put the most common cases first.

Interview FAQs : C++ (Answers End of Post)

1) Which is the parameter that is added to every non-static member function when it is called?
---------------------------------------------------------------------------------------
2)
class base
{
public:
int bval;
base(){ bval=0;}
};
class deri:public base
{
public:
int dval;
deri(){ dval=1;}
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i <>bval;
cout << endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5); }
---------------------------------------------------------------------------------------
3) 
class base { public: void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
4)
class base
{
public:
virtual void baseFun(){ cout << "from base" <<>baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
Deri deriObject;
SomeFunc(&deriObject);
}
---------------------------------------------------------------------------------------
5)
class some
{
public:
~some()
{
cout << "some's destructor" << endl; } }; void main() { some s; s.~some(); } ---------------------------------------------------------------------------------------
6) #include class fig2d { int dim1; int dim2; public: fig2d() { dim1=5; dim2=6;} virtual void operator<<(ostream & rhs); }; void fig2d::operator<<(ostream &rhs) { rhs <<>dim1 <<" "<<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator << (ostream &rhs); }; void fig3d::operator << (ostream &rhs) { fig2d::operator <<(rhs); rhs <<>dim3;
}
*/

void main()
{
fig2d obj1;
// fig3d obj2;
obj1 << cout; // obj2 << cout; }
---------------------------------------------------------------------------------------
7) Class opOverload { Public: bool operator==(opOverload temp); }; bool opOverload::operator==(opOverload temp) { if(*this == temp ) { cout << "The both are same objects\n"; return true; } else { cout << "The both are different\n"; return false; } } void main() { opOverload a1, a2; a1= =a2; }
---------------------------------------------------------------------------------------
8) Class complex { double re; double im; public: complex() : re(1),im(0.5) {} bool operator==(complex &rhs); operator int(){} }; bool complex::operator == (complex &rhs) { if((this->re == rhs.re) && (this->im == rhs.im))
return true;
else
return false;
}
int main()
{
complex c1;
cout << c1;
}
---------------------------------------------------------------------------------------
9)
Class complex
{
double re;
double im;
public:
complex() : re(0),im(0) {}
complex(double n) { re=n,im=n;};
complex(int m,int n) { re=m,im=n;}
void print() { cout << re; cout << im;}
};
void main()
{
complex c3;
double i=5;
c3 = i;
c3.print();
}
---------------------------------------------------------------------------------------
C++ Answer
---------------------------------------------------------------------------------------
1. ‘this’ pointer

00000

2. 01010

3. from base
from base

4. from base
from Derived

5. some's destructor
some's destructor

6. 5 6

7. Runtime Error: Stack Overflow

8. Garbage value

9. 5,5

C Inteview Question

Question :: Read below code and answer the following questions.

 

LINE

Contains

50

char * b, q, *r;

200

b=getbuf();

201

q = *b;

212

r= anotherfunction(b);

213-300

/* we want to use ‘q’ and  ‘r’ here*/

2000

char * getbuf()

2001

{

2002

   char buff[8];

2003-2050

/* unspecified, buff defined here *./

2051

  return (char *) buff;

2052

}




1. What will be in variable ‘q’ after line 201 is executed? Under what conditions might this not be so?
Answer:


2. Is there an alternative, but equivalent, way to write line 2000? If so, what is it?
Answer:



3. Is getbuf() a reasonable function? 
Answer:



4. Will getbuf() execute at all?
Answer:



5. Please comment on line 2051.
Answer:



6. Is getbuf() good practice, and why?
Answer:



7. What line not given should be provided for compilation?
Answer :



(Suggestions and comments are welcome)