C++ Learning Resource Network!

 
 

 C++ Faqs (Frequently Asked Questions with Answers)

 
Question: What is C++?
Answer: C++ is a programming language. It  means "C with Classes", reflecting its nature as an evolution of the C language.
Question: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible ?
Answer: Virtual Constructor doesn't exist.

Constructor canít be virtual as the constructor is a code which is responsible for creating a instance of a class and it canít be delegated to any other object by virtual keyword means.
Question: Is it necessary to already know another programming language before learning C++?
Answer: Not necessarily. C++ is a simple and clear language in its expressions. It is true that a piece of code written with C++ may be seen by a stranger of programming a bit more cryptic than some other languages due to the intensive use of special characters ({}[]*&!|...), but once one knows the meaning of such characters it can be even more schematic and clear than other languages that rely more on English words.
Also, the simplification of the input/output interface of C++ in comparison to C and the incorporation of the standard template library in the language, makes the communication and manipulation of data in a program written in C++ as simple as in other languages, without losing the power it offers.
Question: How can I learn C++?
Answer: There are many ways. Depending on the time you have and your preferences. The language is taught in many types of academic forms throughout the world, and can also be learnt by oneself with the help of tutorials and books. The documentation section of this Website contains an online tutorial to help you achieve the objective of learning this language.
Question: What is Visual C++? And what does "visual programming" mean?
Answer: Visual C++ is the name of a C++ compiler with an integrated environment from Microsoft. It includes special tools that simplify the development of large applications as well as specific libraries that improve productivity. The use of these tools is generally known as visual programming. Other manufacturers also develop these types of tools and libraries, like Borland C++, Visual Age, etc...
Question: What about Virtual Destructor?
Answer: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime depending on the type of object pointer is pointing to , proper destructor will be called.
Question: What is Pure Virtual Function? Why and when it is used ?
Answer: The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.

This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.
Question: What is problem with Runtime type identification?
Answer: The run time type identification comes at a cost of performance penalty. Compiler maintains the class.
Question: How Virtual functions call up is maintained?
Answer: Through Look up tables added by the compile to every class image. This also leads to performance penalty.
Question: Can inline functions have a recursion?
Answer: No.

Syntax wise It is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.
Question: How do you link a C++ program to C functions?
Answer: By using the extern "C" linkage specification around the C function declarations. Programmers should know about mangled function names and type-safe linkages. Then they should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions. Another acceptable answer is "I don't know. We never had to do that." Merely describing what a linker does indicates that the programmer does not understand the issue that underlies the question.
Question: Explain the scope resolution operator?
Answer: It permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
Question: How many ways are there to initialize an int with a constant?
Answer: Two:-

1. int foo = 123;
2. int bar(123);
Question: What is your reaction to this line of code?
delete this;
Answer: It is not a good programming Practice.

A good programmer will insist that you should absolutely never use the statement if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious.

The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster. I think that the language rules should disallow the idiom, but that's another matter.
Question: What is the difference between a copy constructor and an overloaded assignment operator?
Answer: 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.
Question: When should you use multiple inheritance?
Answer: There are three acceptable answers:- "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is a likely and intuitive way to model this common problem domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do.
Question: What is a virtual destructor?
Answer: The simple answer is that a virtual destructor is one that is declared with the virtual attribute.

The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be comple
Question: Can a constructor throw a exception? How to handle the error when the constructor fails?
Answer: The constructor never throws a error.
Question: How the compilers arranges the various sections in the executable image?
Answer: The executable had following sections:-

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

Code Section

Remember that all static variables are allocated in the initialized variable section.
Question: When is a template a better solution than a base class?
Answer: When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus, the generality) to the designer of the container or manager class.
Question: What are the differences between a C++ struct and C++ class?
Answer: The default member and base-class access specifies are different.

This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifies, member functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base-class inheritance, and a class defaults to the private access specified and private base-class inheritance.
Question: How do you know that your class needs a virtual destructor?
Answer: If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a pointer to a base class object. If the destructor is non-virtual, then wrong destructor will be invoked during deletion of the dynamic object.
Question: What is the difference between new/delete and malloc/free?
Answer: Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory.
Question: What happens when a function throws an exception that was not specified by an exception specification for this function?
Answer: Unexpected() is called, which, by default, will eventually trigger abort().
Question: Can you think of a situation where your program would crash without reaching the breakpoint, which you set at the beginning of main()?
Answer: C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
Question: What issue do auto_ptr objects address?
Answer: If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown.
Question: Is there any problem with the following:
char *a=NULL; char& p = *a;?
Answer: The result is undefined. You should never do this. A reference must always refer to some object.
Question: Why do C++ compilers need name mangling?
Answer: Name mangling is the rule according to which C++ changes function's name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.
Question: Is there anything you can do in C++ that you cannot do in C?
Answer: No. There is nothing you can do in C++ that you cannot do in C. After all you can write a C++ compiler in C.
Question: What is an object?
Answer: A region of storage with associated semantics.

For example, int i; "i is an object of type int". In Object Oriented C++, "object" usually means "an instance of a class." Thus a class defines the behavior of possibly many objects.
Question: What is Dangling Pointer?
Answer: A pointer which is pointing to an object which no longer exists is a dangling pointer.
MyClass* p(new MyClass);
MyClass* q = p;
delete p;
p->DoSomething(); // Watch out! p is now dangling!
p = NULL; // p is no longer dangling
q->DoSomething(); // Ouch! q is still dangling!
Question: Why are member functions not virtual by default?
Answer: Because many classes are not designed to be used as base classes.

Also, objects of a class with a virtual function require space needed by
the virtual function call mechanism - typically one word per object. This
overhead can be significant, and can get in the way of layout
compatibility with data from other languages.
Question: Should I use NULL or 0?
Answer: In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided.
That's less common these days.
Question: What is faster ++i or i++, where i is an interger variable?
Answer: The answer to this lies in the fact, how they used. With ++i(PreIncrement) the variable is incremented and new value is returned. So it requires one instruction to increment the variable.

In case of i++(post Increment), the old value has to be returned or used in the expression and then the variable is incrememented after the expression is evaluated. Since you need one instruction to save the old value to be used in the expression and other instruction to increment the variable, its comparatively slower.
Question: Why is "this" not a reference?
Answer: Because "this" was introduced into C++ before references were added.
Question: How are C++ objects laid out in memory?
Answer: Like C, C++ doesn't define layouts, just semantic constraints that must be met. Therefore different implementations do things differently. Unfortunately, the best explanation I know of is in a book that is otherwise outdated and doesn't describe any current C++ implementation: The Annotated C++ Reference Manual (usually called the ARM). It has diagrams of key layout examples. There is a very brief explanation in Chapter 2 of TC++PL.
Basically, C++ constructs objects simply by concatenating sub objects.
Thus

struct A { int a,b; };

is represented by two ints next to each other, and
struct B : A { int c; };

is represented by an A followed by an int; that is, by three ints next to each other. Virtual functions are typically implemented by adding a pointer (the vptr) to each object of a class with virtual functions. This pointer points to the appropriate table of functions (the vtbl). Each class has its own vtbl shared by all objects of that class.
Question: Why doesn't C++ have an equivalent to realloc()?
Answer: If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occationally does copy its argument array.
In C++, a better way of dealing with reallocation is to use a standard library container, such as vector, and let it grow naturally.
Question: Can I mix C-style and C++ style allocation and deallocation?
Answer: Yes, in the sense that you can use malloc() and new in the same program. No, in the sense that you cannot allocate an object with malloc() and free it using delete. Nor can you allocate with new and delete with free () or use realloc() on an array allocated by new.

The C++ operators new and delete guarantee proper construction and destruction; where constructors or destructors need to be invoked, they are. The C-style functions malloc(), calloc(), free(), and realloc() doesn't ensure that. Furthermore, there is no guarantee that the mechanism use by new and delete to acquire and release raw memory is compatible with malloc() and free(). If mixing styles works on your system, you were simply "lucky" - for now.

If you feel the need for realloc() - and many do - then consider using a standard library vector. For example

// read words from input into a vector of strings:

vector words;
string s;
while (cin>>s && s!=".") words.push_back(s);

The vector expands as needed.
Question: What's the value of i++ + i++?
Answer: It's undefined. Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is:
v[i] = i++;

Related example:
f(v[i],i++);

Here, the result is undefined because the order of evaluation of function arguments are undefined. Having the order of evaluation undefined is claimed to yield better performing code. Compilers could warn about such examples, which are
typically subtle bugs (or potential subtle bugs). I'm disappointed that after decades, most compilers still don't warn, leaving that job to specialized, separate, and underused tools.
Question: Write a function to display an integer in a binary format.
Answer: void displayBits( unsigned value )
{
const int SHIFT = 8 * sizeof( unsigned ) - 1;
const unsigned MASK = 1<< SHIFT;
cout << setw(10 ) << value << " = ";
for ( unsigned i = 1; i <= SHIFT + 1; i++ )
{
cout << ( value & MASK ? '1' : '0' );
value <<= 1;

if ( i % 8 == 0 ) // output a space after bits
cout << ' ';
}
cout << endl;
}

You can do the same using divide by 2, until the number is greator than 0. But you will have to use stack to print it in reverse order.
Question: What is Memory Leak?
Answer: Memory which has no pointer pointing to it and there is no way to delete or reuse this memory(object), it causes Memory leak.
{
Base *b = new base();
}
Out of this scope b no longer exists, but the memory it was pointing to was not deleted. Pointer b itself was destroyed when it went out of scope.
Question: Write the hello world program . . . Without using any semi-colon's ";" ?
Answer:

#include

void main()
{
if(printf("Hello World")) { }
}

web metrics

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright © 2008 - 3008  CppTutor.com All rights reserved.