C and C++questions
C and C++questions
If we have Test *var=new Test(), the pointer var will still be valid.
You can get the effect of a virtual constructor by a virtual clone() member function (for copy
constructing), or a virtual create() member function (for the default constructor).
class Shape {
public:
virtual ~Shape() { } // A virtual destructor
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};
void userCode(Shape& s)
{
Shape* s2 = s.clone();
Shape* s3 = s.create();
...
delete s2; // You need a virtual destructor here
delete s3;
}
This function will work correctly regardless of whether the Shape is a Circle, Square, or some other
kind-of Shape that doesn't even exist yet.
Note: The return type of Circle's clone() member function is intentionally different from the return type
of Shape's clone() member function. This is called Covariant Return Types, a feature that was not
originally part of the language. If your compiler complains at the declaration of Circle* clone() const
within class Circle (e.g., saying "The return type is different" or "The member function's type differs
from the base class virtual function by return type alone"), you have an old compiler and you'll have to
change the return type to Shape*.
Anyway, a few words about how virtual functions are commonly implemented: When the C++
compiler finds a class with at least one virtual function, it will create a virtual table (vtable) for that
class. The vtable exists once per class and is basically an array of function pointers. The table is
initialized with the addresses of the actual virtual member functions that class implements. Each
instance of that class carries a pointer to the vtable of its class (the virtual pointer, or vptr) at a fixed
location, usually at the beginning of the memory occupied by the instance. Now when a function call is
encountered, the compiler would normally generate a call to the address of that function. But for virtual
functions calls, the compiler generates code which uses the vprt to look up the function pointer at a
certain index in the vtable, and calls the function through that pointer.
As an example, let's say class A has a virtual function foo(): let's assume that the address of that
function will be placed as the second entry in the vtable of class A. Now a class B is derived from A,
and foo() gets a new implementation in B: The address of B:foo() will be placed at the same index (2)
of B's vtable. Now at runtime we have an A pointer (pA) which points to an instance of B. When we
call foo() through that pointer, the generated code takes the address it finds at the beginning of the
memory pointed to by pA. Since the instance is actually of type B, it will find the address of B's vtable
in the vptr. It will then call the function it finds as the second entry in that table, which is B's
implementation of foo().
C++ virtual function is
C language equivalent exists to a C++ program, then yes you can most certainly do polymorphism in
C. You will have some extra work to get it done.
struct MyClass // remember, in C++ a struct is a class that defaults to public.
{
long _iID;
char _strLabel[16];
MyClass(long iID) : _iID(iID)
{
memset(_strLabel, 0, sizeof _strLabel);
}
virtual bool doSomething();
};
bool MyClass::doSomething()
{
printf("ID = %ld Label = %-*.*s\n", _iID, sizeof(_strLabel), sizeof(_strLabel), _strLabel);
}
/*
C example with data member that is a function pointer used to simulate a virtual method.
Notice how much more verbose the C example is compared to the C++ example above.
*/
#include <stdio.h>
struct MyClass
{
long _iID;
char _strLabel[16];
/*
code for C version of a virtual method. C doesn't have a "this"
pointer so
we have to explicitly create one here.
*/
static bool doSomething(struct MyClass *pThis)
{
printf("ID = %ld Label = %-*.*s\n",
pThis->_iID, sizeof(pThis->_strLabel), sizeof(pThis->_strLabel),
pThis->_strLabel);
}
// C equivalent to a constructor
struct MyClass *newInstance(long iID)
{
struct MyClass *pClass = (struct MyClass *)malloc(sizeof (MyClass) );
if (pClass)
{
pClass->_iID = iID;
memset(pClass->_strLabel, 0, sizeof pClass->_strLabel);
// assign virtual method.
pClass->_pDoSomething = doSomething;
}
return pClass;
}
The auto keyword places the specified variable into the stack area of memory. This is usually
implicit in most variable declarations, e.g. int i;
The extern keyword makes the specified variable access the variable of the same name from some
other file. This is very useful for sharing variables in modular programs.
The register keyword suggests to the compiler to place the particular variable in the fast register
memory located directly on the CPU. Most compilers these days (like gcc) are so smart that
suggesting registers could actually make your program slower.
The static keyword is useful for extending the lifetime of a particular variable. If you declare a static
variable inside a function, the variable remains even after the function call is long gone (the variable is
placed in the alterable area of memory). The static keyword is overloaded. It is also used to declare
variables to be private to a certain file only when declared with global variables. Static can also be used
with functions, making those functions visible only to the file itself.
11. What is Namespace? Namespaces allow to group entities like classes, objects and functions under a
name. This way the global scope can be divided in "sub-scopes", each one with its own name. The
format of namespaces is:
namespace identifier{
entities
}
The size of array is fixed in compile time, so the size of array cannot be adjusted at run time to
accommodate changeling program. But vector can solve this problem by allocating memory as needed.
14. How to write a program such that it will delete itself after execution?
#include <cstdlib>
#include <cstdio>
15. Can we generate a C++ source code from the binary file?
There may be some software that attempts to generate c++ source code from the binary file, but it can
not reproduce the original source code. First, it doesn't know the names of the variables, it doesn't know
how everything was structured, or the names of the functions used. All of these are lost when the code
is compiled. it also can not know what code was optimized.
As far as large programs are concerned (such as a 3D racing game), there's no way you can reproduce
the C++ source code from their binary files. For simple programs, however, you should be able to do
that. Here's how and why.
A binary file is a file that results when you build a C++ program using your compiler and linker. In
order to create a binary, the compiler and the linker go through certain specific steps.
If you know these steps, then, logically, in order to convert the binary back to the C++ code you simply
have to trace these steps backwards.
In the case of large programs, however, that's easier said than done. For complex applications, these
steps of conversion are very very complicated. They are, therefore, almost impossible to understand
and trace backwards.
In the case of a simple program, on the other hand, the path from C++ code to the binary is pretty
straightforward. Consequently, it is relatively far easier to go back from a binary file and arrive at C++
code.
Sure enough, software applications are available that can do the above for you. They are called
disassemblers and decompilers. A disassembler converts a binary to a assembly language code and a
decomplier, as the name suggest, does the opposite of what a compiler does and converts assembly
code into a C++ (or any other high level language) code.
18. How many lines of code you have written for a single program? thousands of lines
The simplest way is to use C++ keywords as variable name, like class, mutable, new, delete and etc.
int main()
{
char* p = malloc(10);
return 0;
}
because of the implicit void* to char* conversion that a C++ compiler won't swallow
class Dummy
{
public:
bool isValid() const;
private:
mutable int size_ = 0;
mutable bool validStatus_ = FALSE; // logical const issue resolved
};
28. What will happen if I allocate memory using "new" and free it using "free" or allocate it using
"calloc" and free it using "delete"?
Memory leak??
33. When shall I use Multiple Inheritance? When to inherit features from more than one class.
1. Non-interactive
2. GNU gdb
3. dbx
Follow http://www.eventhelix.com/RealtimeMantra/Basics/OptimizingCAndCPPCode.htm