C,C++ Questions
C,C++ Questions
Ans:- C structure cannot have member functions but C++ structure can have. Also in a C
structure by default all data members of structure are public and access cannot be
changed by specifying the private or protected keywords but in C++ even though by
default members are public we may change the access using the keywords private and
protected.
Copy Constructor: The copy constructor copies the data values from one object to
another object. When we use statements like c1 c2 where c2 & c1 are the objects of a
class the c++ compiler implicitly creates a copy constructor and copy the values of c2 to
c1.we may also invoke the copy constructor as follows: class name
objectname1(objectname2);
Explanation 2:
Explanation 3:
Therefore if you have a class with dynamic memory allocation a deep copy is required to
guarantee that all members gets copied properly. To make a deep copy you must write a
copy constructor and overload the assignment operator.
class CFoo()
{
public:
// Constructor
CFoo() { m_pArray new char[100]; }
// Destructor
~CFoo() { delete [] m_pArray; }
// Copy constructor
CFoo(const CFoo &refcSource)
{
// Allocate new space
m_pArray new char[strlen(refcSource.m_pArray) + 1];
// Copy values
strcpy(m_pArray refcSource.m_pArray);
}
// Assignment operator
CFoo& operator (const CFoo &refcSource)
{
// Check whether it is the same instance
if(&refcSource ! this)
{
// Release old memory
delete [] m_pArray;
// Copy values
strcpy(m_pArray refcSource.m_pArray);
}
return *this;
}
private:
char *m_pArray;
};
3. What is the difference between "overloading" and "overridding"?
Ans:- Overloading is a process of having the same function name but different no of
arguments or types of arguments within the same class but overriding means redefining a
baseclass functions definition in the subclass.
Overloading means the ability to have more than one form. this is also called
polymorphism. It maybe method or operator overloading.
Overriding occurs when we have same method in both subclass and super class
4. Explain the need for "Virtual Destructor".
Ans: Virtual destructor ensures destruction of subclass and base class objects in proper
order.
virtual destructor is very useful....everyone should use that......if there is no any strong
reason for not using virtual destructor....like...One class having two char variable...........so
it's size is two byte........if u use virtual destructor it's size will be 6 bytes....4 byte for
virtual ptr....Now if this class have 1 millions objects...so 4 magabyte memory will be
lost...where all ptr do the same thing.....
9. What is Namespace?
Ans:1. A vector is a template class but not the array is. So obviously there are members
to access the elements of the vector like, range checking, iterators, insertion/deletion,
predicates, etc.
Since it is a template class, the same implementation can be used for any type including
pointers, objects/user defined types.
2. As said by others, vector automatically grow as we invoke push_back(), we can
reserve additional space for elements, etc.
12. How to write a program such that it will delete itself after execution?
13. Can we generate a C++ source code from the binary file?
Explanation1:
No we cannot generate a c++ source code from the binary file bcoz we can compile
highlevel language to lowlevel language but not lowlevel language to highlevel language
Explanation2:
Both answers might be correct, depending on the situation. This depends highly on the
form of the binary file, particularly on the content and level of debug information
available. Some binary executable files contain no debug information. These can only be
disassembled into non-descriptive assembler codes. Other kinds of binary files contain
full source-level debug information suitable for a full in-circuit-emulator. These can be
used by the emulator software to create full source-level debug information.
You must be clear about what you actually mean with this kind of generic question. The
answer can be highly dependent on the situation.
Inline functions are the functions with the keyword inline written prior to their
declaration in a class.it has the advantage that if a function is made inline than the code of
the called function is placed at the site where it is called.so it obviates the need of
jumping to different addresses acc to how many times it is being called.it is useful in
smallfunctions but for bigger functions normal functions work better.
when a function is called ,the control passes to the location in the memory where it's code
is stored.if the function is called many times then due to this moovement of control many
times between caller and the calle function reduces the speed of the program .by
usinnginline function the moovment of control through and forth caller and callee can be
avoided because the code of the function declared asinline is copied at the place where it
is called in the program.It only useful for small function because large function if copied
in the program it will increase the size of the program.
strstream is the class that specializes iostream to use a strstreambuf for input and output
with arrays of characters in memory. You can create an strstream object by associating
the object with a previously allocated array of characters.
1. When pass by value a copy of object is passed to the called function. Advantage is that
the called function can not alter the value because it is working on a copy, not the actual
variable.
2. Pass by Ref. When a ref is passed, it is the alias. So whatever the called function does
with the ref, the change would be reflected in the original variable too. So this might be
disadvantage too. The method of passing offers advantage of lesser stack memory used.
The mutable keyword can only be applied to non-static and non-const data members of a
class. If a data member is declared mutable, then it is legal to assign a value to this data
member from a const member function.
********************************************
class Mutable
{
private :
int m_iNonMutVar;
mutable int m_iMutVar;
public:
Mutable();
void TryChange() const;
};
Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {};
when we create a const object then none of it's data members can be changed.But if we
want to change some of the data member of a const object we can do so by using mutable
keyword.
ex:
class sample
{
private:
mutable int i;
public:
sample(int x=0)
{
i=x;
}
void fun()const
{
i++;
cout<<i;
}
};
void main()
{
const sample s(15);
s.fun();
}
Void *ptr1;
long *ptr2 = ptr1;
Also you can try compiling this in C it will but not in C++
Code:
int main()
{
int class = 0;
int template = 4;
class += template;
}
21. What will happen if I allocate memory using "new" and free it using "free" or
allocate using "calloc" and free it using "delete"?
When you use calloc function for allocating the memory it won't calls constructor and
when free the memory using delete operator it will call destructor of the class.
so if you are doing any important operations in the constructor it wont be called for
example starting a thread allocate the memory for member varaibles etc..
#include <stdlib.h>
#include <iostream.h>
class CTest
{
public:
CTest()
{
cout<<"nInside Ctor";
}
~CTest()
{
cout<<"nInside Dtor";
}
};
void main()
{
cout<<"nnew and free";
CTest *p new CTest;
free(p);
cout<<"ncalloc and delete";
CTest *p1 (CTest*)calloc(1 sizeof(CTest));
delete p1;
}
Output:
~~~~~
new and free
Inside Ctor
calloc and delete
Inside Dtor
• Maps provide a way of using "associative arrays" that allow you to store data
indexed by keys of any type you desire, instead of just integers as with arrays.
• Maps can be accessed using iterators that are essentially pointers to templated
objects of base type pair, which has two members, first and second. First
corresponds to the key, second to the value associated with the key.
• Maps are fast, guaranteeing O(log(n)) insertion and lookup time.
In fact, the STL's map class allows you to store data by any type of key instead of simply
by a numerical key, the way you must access an array or vector. So instead of having to
compute a hash function and then access an array, you can just let the map class do it for
you.
To use the map class, you will need to include <map> and maps are part of the std
namespace. Maps require two, and possibly three, types for the template:
std::map <key_type, data_type, [comparison_function]>
"Multiple Inheritance is when a derived class inherits properties and methods from
multiple classes as opposed to Single Inheritance. So, for cases where I find that I have
two or more classes and another new class is to be created that has properties and
behaviour of both or all the base classes then I use Multiple inheritance. For example, If
base class one is Terrestrial and Base Class two is Aquatic, then the new class Amphibian
will be case of multiple inheritance deriving from both the two base classes."
Printf is a Variadic function. Variadic functions are functions which may take a variable
number of arguments and are declared with an ellipsis in place of the last parameter.
int printf(char *, ...);
Uses Var_args to know the variables in the ...In C these are defined in stdarg.h
27. How many lines of code you have written for a single program?
29. Write any small program that will compile in "C" but not in "C++"
void main()
{
int class=28;
printf("%d",class);
}
it works...
[class] :p
Pre increment operator is use the concept of value by reference that means it increment
the actual object.
While post increment use call by value concept that is it create the local object, operate
on that, then it will increment actual object, so takes time to create local object
Default constructor
Yes C++ does have a default constructor provided by the compiler. In this case all the
members of the class are initialized to null values. These values act as the default values.
For eg: MyClass me; In the above case since the object is not initialized to any value so
the default constructor will be called which will initialize the class with the default
values.
How can you increase the size of a dynamically allocated array?
ptr realloc(ptr newsize);
This function allocates a new memory space of size newsize to the pointer variable ptr
and returns a pointer to the first byte of the new memory block.
The new size may be smaller or larger than the size.
Above answer is right, but remember If you write down one or more parametric
constructor then If u want to create a object without any parameter then at that
timecompiler doesn't create the empty constructor, you must write down your own empty
constructor.
Array starts with zero because for the easy manipulation start from the whole numbers.
Array is a chunk of continues memory allocation. The arthmetic that is used by compiler
to move to the next array location is -
StartAddress + (Index)*sizeof(int) //if it is an integer array.
now if we see to access the first location of the array we have to give Index =0 and for
next location index =1 and so on...This is why array index start with zero.
Array starts with zero because the opearating syatem is taking 0 also a positive number.
we have int range:-128 to 127
means -128 t0 1 are negative
0 to 127 are positive numbers
total will give the 255 range.
Why Pointers are not used in C Language. What are the main differences between
C and C++
In any application, there can be only one main function. In c++, main is not a member of
any class. There is no chance of overriding
Yes it can possible, behalf of my knowledge we can do it in C language. We can start the
program with our own function and end with the same. But the main constraint is we
must implement (even null) the main function. because the C compiler should not allow
you without main function. This can be happend with #pragma start (function name)
directive.
I have tried in C and it may possible in C++.
Wait() and delay() works same but works on different platforms. Wait(2) will wait
processing fro 2 second on Linux/Unix while delay(2000) with wait for 2 second but on
DOS or Windows.
Funtion over loading is yet another feature of polymorphism.Diff functions with the same
function name but diff arguments are defined in a class.During compile time the
appropriate function is called dep on the arguments passed.Eg:
class area
{
int sq,l,b;
float r;
public:
draw()
{cout<<"no shape"};
float draw(float );
int draw(int );
int draw(int ,int );
};
so dep on the arg passed we get the area of circle square or rectangle.
Yes destructors can be private. But according to Standard Programming practise it is not
advisable to have destructors to be private.
Yes you can put the destructor in the private section of the class. When you don't want to
allow inheritance from your class you need to put the destructor in the private section of
the class. Most of the tutorials say to put the constructor in the private section of the class
to stop inheritance from your class. This is wrong because we can overload the
constructors. So if you put the constructor in the private section of the class i can define
one more constructor and i can start inheritance. But we can't overload the destructor. So
it's better to put destructor in the private section of the class.
Introduction
Multithreading Primer
To explain why synchronization is necessary, you must first take a moment to understand
processes, threads, and thread scheduling. This is a basic overview, so more advanced
readers are advised to skip over to the SlowCopy Example section or to jump ahead to
Part 2.
What is a process?
What is a thread?
A thread is a path of execution—this is where the actual work is done. If you create a
simple console app, and step through the main function in a debugger, you are stepping
through the primary thread of the application. Threads are cool; they can be stopped,
paused, started, and new threads can be created.
Thread scheduling
The system is very fair about which thread gets executed and will execute a thread in a
round robin fashion. For example, say there are five applications running on the system,
each with one thread. The system will execute the thread in app1 for a bit, then move on
to app2 and execute its thread for a bit, and so on. The little bit that I refer to is called a
time slice. As a side note, I'd like to mention that on multiprocessor machines, the round
robin method is still used except the system doles out the workload to more than one
processor. In other words, each thread still gets a time slice, but more than one thread can
be executed simultaneously on different processors.
The algorithm Windows uses to determine thread scheduling is based on many factors,
the details of which aren't really important to writing correct multithreaded applications.
What is important is that Windows remains in control of how long each thread gets
executed. The application itself doesn't have this control and this is a good thing;
otherwise, a 'piggy app' will hog the processor time on a system.
Windows 3.1 used to behave this way. It relied on properly behaving apps to execute
code in small chunks and then give control back to the operating system. Unfortunately,
applications didn't always behave properly, so poorly written apps would tie up the
system.
Thread priorities
The thread scheduling is slightly more complicated by the fact that threads can have
different priorities. Without going into too much detail, the system will always execute
threads with the highest priority before moving on to lower priority threads. A complete
explanation of thread priorities is beyond the scope of this article, so for now I are going
to assume that all your threads have equal priority. By default, a thread is created with a
normal priority, and this will be sufficient for our needs; in fact, most of the time threads
are generally created with normal priority.
Pre-emptive multitasking
On the NT-based operating systems such as Win2000 and XP, the system uses something
called pre-emptive multitasking that keeps the system in control of the thread scheduling.
With pre-emptive multitasking, the system uses the round robin scheme to give each
thread its appropriate time slice. When a thread has used up its allocated time slice, the
system puts that thread to sleep and moves on to giving the next thread a time slice. With
pre-emptive multitasking, it is much more difficult for an errant application to take over
the system (although not impossible).
As I've said earlier, threads exist to perform work and this work often includes reading
and writing data to memory. Thread scheduling and synchronization become important
when more than one thread needs to access the memory (usually referred to as 'shared
memory'). By the waw, I keep referring to shared memory, but really I'm referring to
shared resources whether it's a file, memory, or some other resource.
Because of the pre-emptive nature of the OS, you are not guaranteed that a section of
memory written by one thread has completed fully before the OS has interrupted the
thread to run another thread. The problem occurs when this second thread needs to read
the memory because the first thread may not have completed the write operation.
The complete source code for Parts 1 and 2 is included in the ThreadSync.Zip file located
in the link at the bottom of this article. The ThreadSync.sln consists of the following
projects:
• SlowCopy: This console example illustrates sharing memory between threads
with 1) no synchronization (Part I); 2) native synchronization using a critical
section (Part I); and 3) synchronization using the helper classes (Part II)
• LogSend/LogRcv (Part I): These are two applications that illustrate using helper
classes to protect an std::queue shared between threads and to use a mutex to
protect resources shared between multiple processes.
• OnlyOne (Part II) This is an MFC application that uses a mutex to limit it to a
single instance. In addition, this project uses a memory mapped file to share the
hWnd. This second instance uses this hWnd to bring the first instance into the
foreground before exiting.
SlowCopy Example
To illustrate what can go wrong with sharing data between threads, you are going to need
an example that creates a couple of threads and performs some operation with shared data
that will exhibit memory corruption.
Enter the SlowCopy project in the ThreadSync solution. In the SlowCopy project, you
create two threads: T1 and T2 that share a string. T2's job is to sit in a loop and display
the string whereas the job of T1 is to copy data into the string (while T2 is displaying the
data).
The SlowCopy project is actually multiple projects in one, but rather than having separate
projects—one that copies a string without synchronization, one that copies with native
critical section synchronization, and finally one that copies using synchronization via the
helper classes—I've created one project that uses three different classes derived from a
base class. To view the project without synchronization or with one of the
synchronization methods, the reader is asked to uncomment the appropriate class in the
program main.
One may ask why use C++ inheritance and polymorphism in such a simple example? At
first, this might seem as though it adds unnecessary complexity. However, because our
goal is to take the reader through the synchronization levels from non-synchronized data
sharing to synchronization using native Win32 to finally synchronization using the helper
classes, it makes sense to pull all the thread creation and other common data and methods
into a base class. I feel this is ultimately clearer to the reader because the reader only has
to look at changes to the two virtual methods in each of the derived classes to understand
the code changes of each synchronization level.
The main difference between ASSERT and VERIFY is when you compile the release
build of the program.
ASSERT will not be present in the release build version of the executables/dlls, and its
expression that would have been evaluated will be deleted.
VERIFY will be present in the release build version of the executables/dlls but its
expression that would have been evaluated will be left intact.
ASSERT evaluates the expression only in the debug version and will throw an exception
if the result is 0 and the program termintes.
VERIFY evalutes the expression in Debug and Release version also and if the result is 0,
will throw an exception only in Debug mode.
what is the difference between the codes written in the document class and view
class
The Document class supports objects used to store or control your program's data and
provides the basic functionality for programmer-defined document classes. A document
represents the unit of data that the user typically opens with the Open command on the
File menu and saves with the Save command on the File menu.
The View class provides the basic functionality for programmer-defined view classes. A
view is attached to a document and acts as an intermediary between the document and the
user: the view renders an image of the document on the screen and interprets user input as
operations upon the document. The view also renders the image for both printing
and print preview.
What is persistence?
Persistence is a way of storing state of an object permanently to a file / storage place , etc.
In MFC, CArchive object provide this functionality. "IsStoring" specifies whether the
data is being serialized or de-serialized.
command routing is passing the command to command targeted objects until the
command is handled. If no command targeted objects handle the command finally it
reaches the application object which by default ignores the command.
What are some differences between a form view and a dialog box?
form view is deriving from CFormView and dialog box is deriving from CDialog.
FormView uses CFrameWnd and it can be SDI or MDI application Dialog box only uses
CDialog and CWinApp.
#include <>
#include ""
What is the difference between the cout and cin iostream objects? Answer
#2
1. cin is used to get data from the user and on other hand cout is used
to print the data on the screen for the display.
2. cout and cin both are used under iosteam library.
3. cin operator is ">>" and cout operator is "<<"