reversing the bits in an interger

August 31, 2007

using namespace std;
int main()
unsigned int num; // Reverse the bits in this number.
unsigned int temp = num; // temp will have the reversed bits of num.
cout<<“\n enter the num :”;
int i;
for (i =(sizeof(num)*8-1); i; i–)
temp = temp | (num & 1);
temp <<= 1;
num >>= 1;
temp = temp | (num & 1);

return 0;
//2nd method

//lookup table method

const unsigned char ReverseLookupTable[] =
0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
(table is taken from some sites):)
unsigned int num; // Reverse the bits in this number.
unsigned int temp; // Store the reversed result in this.

temp = (ReverseLookupTable[num & 0xff] << 24) |
(ReverseLookupTable[(num >> 8) & 0xff] << 16) |
(ReverseLookupTable[(num >> 16) & 0xff] << 8) |
(ReverseLookupTable[(num >> 24) & 0xff]);

temp is the reversed-bit number…


abt Lvalue n Rvalue

August 30, 2007

An lvalue can be defined as:“An address in the memory that is the location of an object whose contents can be modified.”

On the other hand, an rvalue can be defined as:”A value that does not necessarily have any storage address. An lvalue can be converted to an rvalue, but _not_ the other way around.”

In the following example, observe the usage of j:

int k, j; /* line 1 */
j = 5; /* line 2*/
k = j; /* line 3*/

The compiler treats the variable j in two different ways: in the line 2, j is the address of the integer object; and in the line 3, it is the value of that object! Technically, j is an lvalue in the line 2; and, a rvalue in the line 3.


An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has a location). An rvalue is any expression that has a value (and that can appear on the right-hand sign of an assignment).

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.

Is an array an expression to which we can assign a value?

An lvalue was defined as an expression to which a value can be assigned. The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes.

The following statement is therefore illegal:

int x[5], y[5];
x = y;

Additionally, you might want to copy the whole array all at once. You can do so using a library function such as the memcpy() function, which is shown here:

memcpy(x, y, sizeof(y));

It should be noted here that unlike arrays, structures can be treated as lvalues.
structure variable to another structure variable of the same type, such as this:
Thus, you can assign one

typedef struct t_name
char last_name[25];
char first_name[15];
char middle_init[2];
NAME my_name, your_name;
your_name = my_name;


what is object in c?

August 30, 2007

The basic unit of data of a running program is an object; and if the program were written in C, then the sizes of objects would vary according to their data types.

So, what is an object? An object can be defined as:

“An object is a contiguous block of memory forming a single logical data structure. Objects are the units of allocation, deallocation, etc., and has a well-defined set of operations.”

Note: We use the term `object’ in a sense introduced by K&R , Objects and Lvalues, which has no relation with Object Oriented Programming.

As per the definition, an object type has a well-defined set of operations that can be applied upon it.  For example, the C language does not allow bit-wise operation on floating types, multiplication on pointer types, and cast operation on lvalues, etc.

C lang construct n diff data types

August 30, 2007

The C programming language offers various data types to suit different purposes.  They can be broadly categorized as follows:

+ Integral types (char, short, int, long, long long, enum, _Bool) (long long and _Bool are new feature of C99)

+ Real floating types (float, double, long double)

+ Complex floating types (float _Complex, double _Complex, long double _Complex) (New feature of C99)

+ void is an empty set of values

+ Derived types (structure type, union type, array type, pointer type, function type)

+ Incomplete type (array of unknown size, a structure or union of unknown content)

Real and complex floating types are collectively know as floating types; integral and floating types are collectively called arithmetic types; arithmetic and pointer types are collectively called scalar types; arrays and structures are collectively called aggregate types.

sorting any char array..danagram..

August 30, 2007

using namespace std;

char a[30];
cout<<“\n enter the char string :”;
int i=0,count=0;
{ count++; i++; }
for(int j=0;j<count;j++)
{ for(i=0;i<count;i++)
{ int temp=a[i];

pring num from 1 to 100(any range) widout using loops

August 29, 2007

using namespace std;

void print(int start,int max)
cout<<start<<” “;

int main ()
int start,max;
cout<<“\n enter the starting num :”;
cout<<“\n enter the max no. :”;

return 0;

return the given char position in any given string n last position

August 29, 2007

using namespace std;
int main ()
char str[80],ch;
cout<<“\n enter the string :”;
cout<<“\n enter the char:->”;
int i=0;
{ cout<<i<<” “; i++;
continue; }

return 0;

//few person ask to return the last position of that particular char in any given string…so just modify lil bit n don print cout<<i<<” “; see below..

//it won work if the given input started from that char like kkkk…. n char=k; //it’ll return 0

using namespace std;
int main ()
char str[80],ch,count[30];
cout<<“\n enter the string :”;
cout<<“\n enter the char:->”;
int i=0,j=0;
{ count[j]=i; j++;
continue; }
int c=strlen(count);
cout<<(int)count[c-1]; //(int)for showing the value otherwise it’ll show address cout<<endl<<endl;
return 0;

//another method beter than previous 

using namespace std;
int main ()
char str[30],ch;
cout<<“\n enter the string :”;
cout<<“\n enter the char:->”;
int i=0,z=0;
{   z=i;
i++; continue; }
cout<<z;    //it’ll print tha last index of that char in given  string
return 0;

question in c/c++..

August 29, 2007

2. Basic C++ Syntax and Semantics.

What Are the Basics of Main()?

What Are the Basics of Functions?

What Are the Basics of Default Parameters?

What Are the Basics of Local (Auto) Objects?

What Are the Basics of Constructing Objects Using Explicit Parameters?

What Are the Basics of Dynamically Allocated (New) Objects?

What Are the Basics of Local Objects within Inner Scopes?

What Are the Basics of Passing Objects by Reference?

What Are the Basics of Passing Objects by Value?

What Are the Basics of Passing Objects by Pointer?

What Are the Basics of Stream Output?

What Are the Basics of Stream Input?

What Are the Basics of Using Classes That Contain Overloaded Operators?

What Are the Basics of Using Container Classes?

What Are the Basics of Creating Class Header Files?

What Are the Basics of Defining a Class?

What Are the Basics of Defining Member Functions?

What Are the Basics of Adding a Constructor to a Class?

What Are the Basics of Adding a Destructor to a Class?

What Are the Basics of Defining a Class That Contains a Pointer to an Object Allocated from the Heap?

What Are the Basics of Global Objects?

What Are the Basics of Throwing and Catching Exceptions?

What Are the Basics of Inheritance and Dynamic Binding?

3. Understanding the Management Perspective.

Why Are the Managers in Charge Rather Than the Developers Who Understand Technology?

How Can Someone Manage Something They Don’t Understand?

What Is the Most Common Mistake on C++ and OO Projects?

What’s the “Software Peter Principle?”

Should an Organization Use OO on All Its Projects?

Can OO Be Ignored Until It Goes Away?

What OO Language Is Best?

What Is the Right Approach to Processes and Tools?

What Is the Right Approach with Off-the-Shelf Class Libraries and Frameworks?

4. The Architectural Perspective.

Why Is Software Architecture Important?

What Should the Architecture Be Based on, the Problem Being Solved or the Problem Domain?

Should the Software Architecture Be Based on the Policy of the Problem?

Do Customers Ever Change Their Requirements?

Are Stable Requirements Desirable?

What Is the Key to Planning for Change?

What Is a Framework?

What Is the “Inversion of Control” Exhibited by Frameworks?

What Is an Extensible, Domain-Specific Framework?

What Characteristics Make a Framework Extensible Yet Domain-Specific?

What Happens if the Domain Analysis Is Incorrect?

How Much Effort Should Be Expended to Support Change — That Is, How Much Is Extensibility Worth?

How Does an Architect Make the Software Architecture Flexible?

What Is the Secret to Achieving Reuse?


5. Object-Oriented Fundamentals.

Why Is the World Adopting OO Technology?

What Are Some of the Benefits of Using C++ for OO Programming?

What Are the Fundamental Concepts of Object-Oriented Technology?

Why Are Classes Important?

What Is an Object?

What Are the Desirable Qualities of an Object?

How Are Classes Better Than the Three Basic Building Blocks of Procedural Software?

What Is the Purpose of Composition?

What Is the Purpose of Inheritance?

What Are the Advantages of Polymorphism and Dynamic Binding?

How Does OO Help Produce Flexible and Extensible Software?

How Can Old Code Call New Code?

What Is an Abstraction and Why Is It Important?

Should Abstractions Be User-Centric or Developer-Centric?

What’s the Difference between Encapsulation and Abstraction?

What Are the Consequences of Encapsulating a Bad Abstraction?

What’s the Value of Separating Interface from Implementation?

How Can Separating Interface from Implementation Improve Performance as Well as Flexibility?

What Is the Best Way to Create a Good Interface to an Abstraction?

How Are Get/Set Member Functions Related to Poorly Designed Interfaces?

Should There Be a Get and a Set Member Function for Each Member Datum?

Is the Real Purpose of a Class to Export Data?

Should OO Be Viewed as Data-Centric?

6. Specification of Observable Behavior.

Should Users of a Member Function Rely on What the Code Actually Does or on the Specification?

What Are the Advantages of Relying on the Specification Rather Than the Implementation?

What Are Advertised Requirements and Advertised Promises?

How Are the Advertised Requirements and Advertised Promises of the Member Functions Specified?

Why Are Changes Feared in Development Organizations That Don’t Use Specification?

How Do Developers Determine if a Proposed Change Will Break Existing Code?

What Are the Properties of a Substitutable (Backward Compatible) Change in a Specification?

How Can It Be Shown That the Implementation of a Member Function Fulfills Its Specification?

Is It Possible to Keep the Specification Synchronized with the Code?

7. Proper Inheritance.

What Is Proper Inheritance?

What Are the Benefits of Proper Inheritance?

What Is Improper Inheritance?

Isn’t the Difference between Proper and Improper Inheritance Obvious?

Is Substitutability Based on What the Code Does or What the Specification Promises the Code Will Do?

Is It Proper to Revoke (Hide) an Inherited Public: Member Function?

What Is Specialization?

What Do Subsets Have to Do with Proper Inheritance?

8. Detecting and Correcting Improper Inheritance.

Can Improper Inheritance Wreck a Project?

What’s the Best Way to Learn How to Avoid Improper Inheritance?

Is Intuition a Reliable Guide to Understanding Proper Inheritance?

Is an Ostrich a Kind-Of Bird?

Should an Overridden Virtual Function Throw an Exception?

Can an Overridden Virtual Function Be a No-Op?

Why Does C++ Make It So Hard to Fix the Ostrich/Bird Dilemma?

Should Circle Inherit from Ellipse?

What Can Be Done about the Asymmetric-Circle Dilemma?

What Is the One Issue in These FAQs That Doesn’t Seem to Die?

Should Stack Inherit from List?

Is Code Reuse the Main Purpose of Inheritance?

Is Container-of-Thing a Kind-Of Container-of-Anything?

Is Bag-of-Apple a Kind-Of Bag-of-Fruit, Assuming Bag-of-Fruit Allows the Insertion of Any Kind-Of Fruit?

Is Parking-Lot-for-Cars a Kind-Of Parking-Lot-for-Arbitrary-Vehicles (Assuming Parking-Lot-for-Vehicles Allows Parking Any Kind-Of Vehicle)?

Is Array-Of Derived a Kind-Of Array-Of Base?

Does the Fact That an Array-Of Derived Can Be Passed as an Array-Of Base Mean That Arrays Are Bad?

9. Error Handling Strategies.

Is Error Handling a Major Source of Fundamental Mistakes?

How Should Runtime Errors Be Handled in C++?

What Happens to Objects in Stack Frames That Become Unwound During the Throw / Catch Process?

What Is an Exception Specification?

What Are the Disadvantages of Using Return Codes for Error Handling?

What Are the Advantages of Throw…Catch?

Why Is It Helpful to Separate Normal Logic from Exception Handling Logic?

What Is the Hardest Part of Using Exception Handling?

When Should a Function Throw an Exception?

What Is the Best Approach for the Hierarchy of Exception Objects?

How Should Exception Classes Be Named?

Where Do Setjmp and Longjmp Belong in C++?

10. Testing Strategies.

What Are the Advantages of Self-Testing Objects?

What Are Some Common Excuses People Use for Not Building Self-Testing Into Their Objects?

What Will Happen if Techniques Like Those Presented Here Are Not Used?

When Is a Class Correct?

What Is Behavioral Self-Testing?

What Is a Class Invariant?

Why Should the Invariant Be Captured Explicitly?

When Should the Testinvariant() Member Function Be Called?

What Can Be Done to Ensure That an Object Doesn’t Get Blown Away by a Wild Pointer?


11. References.

What Is a Reference?

What Does “Referent” Mean?

When Can a Reference Be Attached to Its Referent?

What Happens When a Value Is Assigned to a Reference?

What Is a Local Reference?

What Does It Mean to Return a Reference?

What Is the Result of Taking the Address of a Reference?

Can a Reference Be Made to Refer to a Different Referent?

Why Use References When Pointers Can Do Everything References Can Do?

Aren’t References Just Pointers in Disguise?

When Are Pointers Needed?

Why Do Some People Hate References?

Does Int& Const X Make Sense?

12. New and Delete.

Does New Do More Than Allocate Memory?

Why Is New Better Than Good Old Trustworthy Malloc()?

Does C++ Have a Counterpart to Realloc() That Goes Along with New and Delete?

Can Pointers Returned from New Be Deallocated with Free()? Can Pointers Returned from Malloc() Be Deallocated with Delete?

Does Delete P Delete the Pointer P or the Referent *P?

Should the Pointer Returned from New Fred() Be Checked to See if It Is NULL?

How Can New Be Convinced to Return NULL Rather Than Throw an Exception?

How Can New Be Set Up to Automatically Flush Pools of Recycled Objects Whenever Memory Runs Low?

What Happens if Delete P Is Called When P Is NULL?

What Happens When a Pointer Is Deleted Twice?

How Can an Array of Things Be Allocated and Deallocated?

What if Delete P (Not Delete[] P) Is Used to Delete an Array Allocated Via New Fred[N]?

Can the [] of Delete[] P Be Dropped When P Points to an Array of Some Built-in Type Such as Char?

How Is an Object Constructed at a Predetermined Position in Memory?

How Can Class Fred Guarantee That Fred Objects Are Created Only with New and Not on the Stack?

How Are Objects Created by Placement New Destroyed?

in P = New Fred(), Does the Fred Memory “Leak” if the Fred Constructor Throws an Exception?

Is It Legal (and Moral) for a Member Function to Say Delete This?

After P = New Fred[N], How Does the Compiler Know That There Are N Objects to Be Destructed During Delete[] P?

13. Inline Functions.

What Is the Purpose of Inline Functions?

What Is the Connection between the Keyword “Inline” and “Inlined” Functions?

Are There Any Special Rules about Inlining?

What Is the One-Definition Rule (ODR)?

What Are Some Performance Considerations with Inline Functions?

Do Inlined Functions Improve Performance?

Do Inlined Functions Increase the Size of the Executable Code?

Why Shouldn’t the Inlining Decision Be Made When the Code Is First Written?

What Happens When a Programmer Uses an Inlined Function Obtained from a Third Party?

Is There an Easy Way to Swap between Inline and Non-Inline Code?

14. Const Correctness.

How Should Pointer Declarations Be Read?

How Can C++ Programmers Avoid Making Unexpected Changes to Objects?

Does Const Imply Runtime Overhead?

Does Const Allow the Compiler to Generate More Efficient Code?

Is Const Correctness Tedious?

Why Should Const Correctness Be Done Sooner Rather Than Later?

What’s the Difference between an Inspector and a Mutator?

When Should a Member Function Be Declared as Const?

Does Const Apply to the Object’s Bitwise State or Its Abstract State?

When Should Const Not Be Used in Declaring Formal Parameters?

When Should Const Not Be Used in Declaring a Function Return Type?

How Can a “Nonobservable” Data Member Be Updated within a Const Member Function?

Can an Object Legally Be Changed Even Though There Is a Const Reference (Pointer) to It?

Does Const_Cast Mean Lost Optimization Opportunities?

15. Namespaces.

What Is a Namespace?

How Can Code Outside a Namespace Use Names Declared within That Namespace?

What Happens if Two Namespaces Contain the Same Name?

What Are Some of the Rules for Using Namespaces?

What Is Name Lookup?

What Are the Tradeoffs between the Various Techniques for Using Names from a Namespace, Particularly the Standard Namespace?

Can Namespaces Break Code?

Do Namespaces Have Any Other Applications?

How Do Namespaces Solve the Problem of Long Identifiers?

16. Using Static.

What Are Static Class Members?

What Is an Analogy for Static Data Members?

Can Inline Functions Safely Access Static Data Members?

What Is an Analogy for Static Member Functions?

How Is a Static Data Member Similar to a Global Variable?

How Is a Static Member Function Similar to a Friend Function?

What Is the Named Constructor Idiom?

How Should Static Member Functions Be Called?

Why Might a Class with Static Data Members Get Linker Errors?

How Is a Const Static Data Member Initialized?

What Is the Right Strategy for Implementing a Function That Needs to Maintain State between Calls?

How Can the Function Call Operator Help with Functionoids?

Is It Safe to Be Ignorant of the Static Initialization Order Problem?

What Is a Simple and Robust Solution to the Static Initialization Order Problem?

What if the Static Object’s Destructor Has Important Side Effects That Must Eventually Occur?

What if the Static Object’s Destructor Has Important Side Effects That Must Eventually Occur and the Static Object Must Be Accessed by Another Static Object’s Destructor?

What Are Some Criteria for Choosing between All These Various Techniques?

17. Derived Classes.

How Does C++ Express Inheritance?

What Is a Concrete Derived Class?

Why Can’t a Derived Class Access the Private: Members of Its Base Class?

How Can a Base Class Protect Derived Classes So That Changes to the Base Class Will Not Affect Them?

Can a Derived Class Pointer Be Converted Into a Pointer to Its Public Base Class?

How Can a Class Y Be a Kind-Of Another Class X as Well as Getting the Bits of X?

How Can a Class Y Get the Bits of an Existing Class X Without Making Y a Kind-Of X?

How Can a Class Y Be a Kind-Of Another Class X Without Inheriting the Bits of X?

18. Access Control.

How Are Private:, Protected:, and Public: Different?

Why Can’t Subclasses Access the Private: Parts of Their Base Class?

What’s the Difference between the Keywords Struct and Class?

When Should a Data Member Be Protected: Rather Than Private:?

Why Is Private: the Default Access Level for a Class?

19. Friend Classes and Friend Functions.

What Is a Friend?

What’s a Good Mental Model for Friend Classes?

What Are Some Advantages of Using Friend Classes?

Do Friends Violate the Encapsulation Barrier?

What Is a Friend Function?

When Should a Function Be Implemented as a Friend Function Rather Than a Member Function?

What Are Some Guidelines to Make Sure Friend Functions Are Used Properly?

What Does It Mean That Friendship Isn’t Transitive?

What Does It Mean That Friendship Isn’t Inherited?

What Does It Mean That Friends Aren’t Virtual?

What Qualities Suggest a Friend Function Rather Than a Member Function?

Should Friend Functions Be Declared in the Private:, Protected:, or Public: Section of a Class?

What Is a Private Class?

How Are Objects of a Class Printed?

How Do Objects of a Class Receive Stream Input?

20. Constructors and Destructors.

What Is the Purpose of a Constructor?

What Is C++’S Constructor Discipline?

What Is the Purpose of a Destructor?

What Is C++’S Destructor Discipline?

What Happens When a Destructor Is Executed?

What Is the Purpose of a Copy Constructor?

When Is a Copy Constructor Invoked?

What Is the “Default Constructor?”

Should One Constructor Call Another Constructor as a Primitive?

Does the Destructor for a Derived Class Need to Explicitly Call the Destructor of Its Base Class?

How Can a Local Object Be Destructed Before the End of Its Function?

What Is a Good Way to Provide Intuitive, Multiple Constructors for a Class?

When the Constructor of a Base Class Calls a Virtual Function, Why Isn’t the Override Called?

When a Base Class Destructor Calls a Virtual Function, Why Isn’t the Override Called?

What Is the Purpose of Placement New?

21. Virtual Functions.

What Is a Virtual Member Function?

How Much Does It Cost to Call a Virtual Function Compared to Calling a Normal Function?

How Does C++ Perform Static Typing While Supporting Dynamic Binding?

Can Destructors Be Virtual?

What Is the Purpose of a Virtual Destructor?

What Is a Virtual Constructor?

What Syntax Should Be Used When a Constructor or Destructor Calls a Virtual Function in Its Object?

Should the Scope Operator :: Be Used When Invoking Virtual Member Functions?

What Is a Pure Virtual Member Function?

Can a Pure Virtual Function Be Defined in the Same Class That Declares It?

How Should a Virtual Destructor Be Defined When It Has No Code?

Can an ABC Have a Pure Virtual Destructor?

How Can the Compiler Be Kept from Generating Duplicate Out-Lined Copies of Inline Virtual Functions?

Should a Class with Virtual Functions Have at Least One Non-Inline Virtual Function?

22. Initialization Lists.

What Are Constructor Initialization Lists?

What Will Happen if Constructor Initialization Lists Are Not Used?

What’s the Guideline for Using Initialization Lists in Constructor Definitions?

Is It Normal for Constructors to Have Nothing Inside Their Body?

How Is a Const Data Member Initialized?

How Is a Reference Data Member Initialized?

Are Initializers Executed in the Same Order in Which They Appear in the Initialization List?

How Should Initializers Be Ordered in a Constructor’s Initialization List?

Is It Moral for One Member Object to Be Initialized Using Another Member Object in the Constructor’s Initialization List?

What if One Member Object Has to Be Initialized Using Another Member Object?

Are There Exceptions to the Rule “Initialize All Member Objects in an Initialization List?”

How Can an Array of Objects Be Initialized with Specific Initializers?

23. Operator Overloading.

Are Overloaded Operators Like Normal Functions?

When Should Operator Overloading Be Used?

What Operators Can’t Be Overloaded?

Is the Goal of Operator Overloading to Make the Class Easier to Understand?

Why Do Subscript Operators Usually Come in Pairs?

What Is the Most Important Consideration for Operators Such as +=, +, and =?

How Are the Prefix and Postfix Versions of Operator++ Distinguished?

What Should the Prefix and Postfix Versions of Operator++ Return?

How Can a Matrix-Like Class Have a Subscript Operator That Takes More Than One Subscript?

Can a ** Operator Serve as an Exponentiation Operator?

24. Assignment Operators.

What Should Assignment Operators Return?

What Is Wrong with an Object Being Assigned to Itself?

What Should Be Done about Self-Assignment?

Should an Assignment Operator Throw an Exception After Partially Assigning an Object?

How Should the Assignment Operator Be Declared in an ABC?

When Should a User-Defined Assignment Operator Mimic the Assignment Operator That the Compiler Would Generate Automatically?

What Should Be Returned by Private: and Protected: Assignment Operators?

Are There Techniques That Increase the Likelihood That the Compiler-Synthesized Assignment Operator Will Be Right?

How Should the Assignment Operator in a Derived Class Behave?

Can an ABC’s Assignment Operator Be Virtual?

What Should a Derived Class Do a Base Class’s Assignment Operator Is Virtual?

Should the Assignment Operator Be Implemented by Using Placement New and the Copy Constructor?

25. Templates.

What Is the Purpose of Templates?

What Are the Syntax and Semantics for a Class Template?

How Can a Template Class Be Specialized to Handle Special Cases?

What Are the Syntax and Semantics for a Function Template?

Should a Template Use Memcpy() to Copy Objects of Its Template Argument?

Why Does the Compiler Complain about >&Gt; When One Template Is Used Inside Another?

26. Exception Tactics.

What Belongs in a Try Block?

When Should a Function Catch an Exception?

Should a Catch Block Fully Recover from an Error?

How Should a Constructor Handle a Failure?

What Are Zombie Objects (and Why Should They Be Avoided)?

What Should an Object Do if One of Its Member Objects Could Throw an Exception During Its Constructor?

Should Destructors Throw Exceptions When They Fail?

Should Destructors Call Routines That May Throw Exceptions?

Should Resource Deallocation Primitives Signal Failure by Throwing an Exception?

What Should the Terminate() Function Do?

What Should the Unexpected() Function Do?

Under What Circumstances Can an Overridden Virtual Member Function Throw Exceptions Other Than Those Listed by the Specification of the Member Function in the Base Class?

How Might the Exception-Handling Mechanism Cause a Program to Silently Crash?

27. Types and RTTI.

What Is Static Type Checking?

What Is Dynamic Type Checking?

What Is the Basic Problem with Dynamic Type Checking?

How Can Dynamic Type Checking Be Avoided?

Are There Better Alternatives to Dynamic Type Checking?

What Is a Capability Query?

What Is an Alternative to Dynamic Type Checking with Containers?

Are There Cases Where Dynamic Type Checking Is Necessary?

Given a Pointer to an ABC, How Can the Class of the Referent Be Found?

What Is a Downcast?

What Is an Alternative to Using Downcasts?

Why Are Downcasts Dangerous?

Should the Inheritance Graph of C++ Hierarchies Be Tall or Short?

Should the Inheritance Graph of C++ Hierarchies Be Monolithic or a Forest?

What Is Runtime Type Identification (RTTI)?

What Is the Purpose of Dynamic_Cast&Lt;T&Gt;()?

Is Dynamic_Cast&Lt;T&Gt;() a Panacea?

What Does Static_Cast&Lt;T&Gt;() Do?

What Does Typeid() Do?

Are There Any Hidden Costs for Type-Safe Downcasts?

28. Containers.

What Are Container Classes and What Are the Most Common Mistakes Made with Container Classes?

Are Arrays Good or Evil?

Should Application Development Organizations Create Their Own Container Classes?

What Are Some Common Mistakes with Containers of Pointers?

Does This Mean That Containers of Pointers Should Be Avoided?

Surely Good Old-Fashioned Char* Is an Exception, Right?

Can Auto_Ptr&Lt;T&Gt; Simplify Ownership Problems with Containers of Pointers?

Can a Java-Like Object Class Simplify Containers in C++?

What’s the Difference between a Homogeneous and a Heterogeneous Container?

Is It a Good Idea to Use a “Best of Breed” Approach When Selecting Container Classes?

Should All Projects Use C++’S Standardized Containers?

What Are the C++ Standardized Container Classes?

What Are the Best Applications for the Standardized C++ Sequence Container Classes?

What Are the Best Situations for the Standardized C++ Associative Container Classes?


29. Mixing Overloading with Inheritance.

What Is the Difference between Overloaded Functions and Overridden Functions?

What Is the Hiding Rule?

How Should the Hiding Rule Be Handled?

What Should a Derived Class Do When It Redefines Some but Not All of a Set of Overloaded Member Functions Inherited from the Base Class?

Can Virtual Functions Be Overloaded?

30. The Big Three.

What Are the Big Three?

What Happens When an Object Is Destroyed That Doesn’t Have an Explicit Destructor?

What Happens if an Object Is Copied but Doesn’t Have an Explicit Copy Constructor?

What Happens When an Object That Doesn’t Have an Explicit Assignment Operator Is Assigned?

What Is the Law of the Big Three?

Which of the Big Three Usually Shows Up First?

What Is Remote Ownership?

How Is Remote Ownership Special?

What if a Class Owns a Referent and Doesn’t Have All of the Big Three?

Are There Any C++ Classes That Help Manage Remote Ownership?

Does Auto_Ptr Enforce the Law of the Big Three and Solve the Problems Associated with Remote Ownership?

Are There Cases Where One or Two of the Big Three May Be Needed but Not All Three?

Are There Any Other Circumstances That Might Explicitly Warrant the Big Three?

Why Does Copying an Object Using Memcpy() Cause a Program Crash?

Why Do Programs with Variable-Length Argument Lists Crash?

Why Do Programs That Use Realloc() to Reallocate an Array of Objects Crash?

31. Using Objects to Prevent Memory Leaks.

When Are Memory Leaks Important?

What Is the Easiest Way to Avoid Memory Leaks?

What Are the Most Important Principles for Resource Management?

Should the Object That Manages a Resource Also Perform Operations That May Throw Exceptions?

Should an Object Manage Two or More Resources?

What if an Object Has a Pointer to an Allocation and One of the Object’s Member Functions Deletes the Allocation?

How Should a Pointer Variable Be Handled After Being Passed to Delete?

What Should Be Done with a Pointer to an Object That Is Allocated and Deallocated in the Same Scope?

How Easy Is It to Implement Reference Counting with Pointer Semantics?

Is Reference Counting with Copy-on-Write Semantics Hard to Implement?

How Can Reference Counting Be Implemented with Copy-on-Write Semantics for a Hierarchy of Classes?

32. Wild Pointers and Other Devilish Errors.

What Is a Wild Pointer?

What Happens to a Program That Has Even One Wild Pointer?

What Does the Compiler Mean by the Warning “Returning a Reference to a Local Object?”

How Should Pointers Across Block Boundaries Be Controlled?

Is the Reference-Versus-Pointer Issue Influenced by Whether or Not the Object Is Allocated from the Heap?

When Should C-Style Pointer Casts Be Used?

Is It Safe to Bind a Reference Variable to a Temporary Object?

Should a Parameter Passed by Const Reference Be Returned by Const Reference?

Should Template Functions for Things Like Min(X,Y) or Abs(X) Return a Const Reference?

When Is Zero Not Necessarily Zero?

33. High-Performance Software.

Is Bad Performance a Result of Bad Design or Bad Coding?

What Are Some Techniques for Improving Performance?

What Is an Advantage of Using Pointers and References?

What Is a Disadvantage of Lots of References and Pointers?

How Else Can Member Objects Improve Performance Over Pointers?

Which Is Better, ++I or I++?

What Is the Performance Difference between Fred X(5); and Fred Y = 5; and Fred Z = Fred(5);?

What Kinds of Applications Should Consider Using Final Classes and Final Member Functions?

What Is a Final Class?

What Is a Final Member Function?

How Can Final Classes and Final Member Functions Improve Performance?

When Should a Nonfinal Virtual Function Be Invoked with a Fully Qualified Name?

Should Full Qualification Be Used When Calling Another Member Function of the Same Class?

Do Final Classes and Final Member Functions Cause a Lot of Code Duplication?

Why Do Some Developers Dislike Final Member Functions and Final Classes?

Can a Programming Language — Rather Than Just the Compiler — Affect the Performance of Software?

34. COM and Active X.

What Is the Component Object Model?

What Are Activex and OLE?

What Does the Name Component Object Model Mean?

What Is a “Binary Object Model?”

What Are the Key Features of COM?

What Are Guids?

Why Does COM Need Guids (and Clsids and Iids)?

What Is an Interface?

What Is the Iunknown Interface?

How Many Ways Are There to Specify COM Interfaces?

What Are COM Classes and COM Objects?

How Hard Is It for Callers to Create and Use a COM Object?

How Does COM Provide Language Transparency?

How Does COM Provide Location Transparency?

What Types of Errors Occur Due to Reference Counting?

What Mechanism Does COM Define for Error Handling?

How Are Interfaces Versioned?

Is COM Object Oriented?

What Is the Biggest Problem with COM?

What Are the Major Differences between COM and C++?

When Should a Class Be Defined as a COM Class?

What Is Automation?

What Are Dispatch Interfaces?

When Should a Class Expose a Dispatch Interface?

How Does Automation Work?

How Does Invoke Accomplish All of This?

What Is a Type Library?

What Are the Benefits of Using Type Libraries?

How Do Type Libraries Improve Performance?

What Are Dual Interfaces?

What Limitations Are There on Dual Interfaces?

What Are OLE Custom Controls and Activex Controls?

Why Do Activex Controls Differ from OLE Custom Controls?

What Is a Control Container?

What Are Component Categories?

What Are Events?

What Is DCOM?

How Stable Is DCOM’s Infrastructure?

What Is COM+?

35. Transitioning to CORBA.

What Is CORBA?

What Is an ORB?

What Is IDL?

What Is COS?

What Is OMA?

What Is OMG?

What Are the Important Concepts Behind CORBA?

Isn’t OMG IDL Pretty Much the Same as C++?

Is the Lifecycle of a CORBA Object the Same as the Lifecycle of a C++ Object?

Is the C++ Code That Interacts with the CORBA Implementation Portable to a Different CORBA Vendor?

How Do CORBA Exceptions Compare to C++ Exceptions?

Which CORBA Implementation Is Best? Is CORBA Better Than COM?

36. C Language Considerations.

What Are the Main Issues When Mixing C and C++ Code in the Same Application?

How Can C++ Code Call C Code?

How Can C Code Call C++ Code?

Why Is the Linker Giving Errors for C Functions Called from C++ Functions and Vice Versa?

How Can an Object of a C++ Class Be Passed to or from a C Function?

Can a C Function Directly Access Data in an Object of a C++ Class?

Can C++ I/O (&Lt;Iostream&Gt;) Be Mixed with C I/O (&Lt;Stdio.H&Gt;)?

Which Is Safer: &Lt;Iostream&Gt; or &Lt;Stdio.H&Gt;?

Which Is More Extensible: &Lt;Iostream&Gt; or &Lt;Stdio.H&Gt;?

Which Is More Flexible: &Lt;Iostream&Gt; or &Lt;Stdio.H&Gt;?

Why Does It Seem That C++ Programming Feels Farther Away from the Machine Than C?

Why Does C++ Do More Things Behind Your Back Than C Does?

37. Private and Protected Inheritance.

What Are Private Inheritance and Protected Inheritance?

What Is the Difference between Private Inheritance and Protected Inheritance?

What Is the Syntax and Semantics for Private and Protected Inheritance?

When Should Normal Has-a Be Used, Rather Than Private or Protected Inheritance?

What Are the Access Rules for Public, Protected, and Private Inheritance?

In a Private or Protected Derived Class, How Can a Member Function That Was Public in the Base Class Be Made Public in the Derived Class?

Should a Pointer Be Cast from a Private or Protected Derived Class to Its Base Class?

38. Pointers to Member Functions.

What Is the Type of a Pointer to a Nonstatic Member Function?

Can Pointers to Nonstatic Member Functions Be Passed to Signal Handlers, X Event Call-Back Handlers, and So on, That Expect C-Like Function Pointers?

What Is One of the Most Common Errors When Using Pointers to Member Functions?

How Is an Array of Pointers to Nonstatic Member Functions Declared?

39. The Transition to OO and C++.

How Many Stages of Technical Expertise Are There in the Transition?

Why Bother Defining Levels of Expertise?

Can OO/C++ Be Learned from a Book?

Can OO/C++ Be Learned from a Course?

What Is the Key to Learning OO/C++?

Are Small Projects a Good Way to Get Your Feet Wet?

Does Being a Good C Programmer Help When Learning OO/C++?

What Skills Help When Learning OO/C++?

Why should I use inline functions instead of plain old #define macros?

August 29, 2007

Unlike #define macros, inline functions avoid infamous macro errors since inline functions always evaluate every argument exactly once. In other words, invoking an inline function is semantically just like invoking a regular function, only faster:

// A macro that returns the absolute value of i
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )

// An inline function that returns the absolute value of i
int safe(int i)
return i >= 0 ? i : -i;

int f();

void userCode(int x)
int ans;

ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice

ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once

Also unlike macros, argument types are checked, and necessary conversions are performed correctly.

Do inline functions improve performance?

August 29, 2007

Yes and no. Sometimes. Maybe.

There are no simple answers. inline functions might make the code faster, they might make it slower. They might make the executable larger, they might make it smaller. They might cause thrashing, they might prevent thrashing. And they might be, and often are, totally irrelevant to speed.

inline functions might make it faster:  procedural integration might remove a bunch of unnecessary instructions, which might make things run faster.

inline functions might make it slower: Too much inlining might cause code bloat, which might cause “thrashing” on demand-paged virtual-memory systems. In other words, if the executable size is too big, the system might spend most of its time going out to disk to fetch the next chunk of code.

inline functions might make it larger: This is the notion of code bloat, as described above. For example, if a system has 100 inline functions each of which expands to 100 bytes of executable code and is called in 100 places, that’s an increase of 1MB. Is that 1MB going to cause problems? Who knows, but it is possible that that last 1MB could cause the system to “thrash,” and that could slow things down.

inline functions might make it smaller: The compiler often generates more code to push/pop registers/parameters than it would by inline-expanding the function’s body. This happens with very small functions, and it also happens with large functions when the optimizer is able to remove a lot of redundant code through procedural integration — that is, when the optimizer is able to make the large function small.

inline functions might cause thrashing: Inlining might increase the size of the binary executable, and that might cause thrashing.

inline functions might prevent thrashing: The working set size (number of pages that need to be in memory at once) might go down even if the executable size goes up. When f() calls g(), the code is often on two distinct pages; when the compiler procedurally integrates the code of g() into f(), the code is often on the same page.

inline functions might increase the number of cache misses: Inlining might cause an inner loop to span across multiple lines of the memory cache, and that might cause thrashing of the memory-cache.

inline functions might decrease the number of cache misses: Inlining usually improves locality of reference within the binary code, which might decrease the number of cache lines needed to store the code of an inner loop. This ultimately could cause a CPU-bound application to run faster.

inline functions might be irrelevant to speed: Most systems are not CPU-bound. Most systems are I/O-bound, database-bound or network-bound, meaning the bottleneck in the system’s overall performance is the file system, the database or the network. Unless your “CPU meter” is pegged at 100%, inline functions probably won’t make your system faster. (Even in CPU-bound systems, inline will help only when used within the bottleneck itself, and the bottleneck is typically in only a small percentage of the code.)

There are no simple answers: You have to play with it to see what is best. Do not settle for simplistic answers like, “Never use inline functions” or “Always use inline functions” or “Use inline functions if and only if the function is less than N lines of code.” These one-size-fits-all rules may be easy to write down, but they will produce sub-optimal results.