VIRTUAL FunctionWhat is a Virtual Function?
A virtual function is a member function of a class, whose functionality can be over-ridden in its derived classes. It is one that is declared as virtual in the base class using the virtual keyword. The virtual nature is inherited in the subsequent derived classes and the virtual keyword need not be re-stated there. The whole function body can be replaced with a new set of implementation in the derived class.
How does a Virtual Function work?
Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.
The following code shows how we can write a virtual function in C++ and then use the same to achieve dynamic or run time polymorphism.
#include
class base {
public:
virtual void display() {
cout<<”\nBase”; }
};
class derived : public base {
public:
void display() {
cout<<”\nDerived”;
}
};
void main() {
base *ptr = new derived();
ptr->display();
}
In the above example, the pointer is of type base but it points to the derived class object. The method display() is virtual in nature. Hence in order to resolve the virtual method call, the context of the pointer is considered, i.e., the display method of the derived class is called and not that of the base. If the method was non virtual in nature, the display() method of the base class would have been called.
Properties of Virtual Functions:
• Dynamic Binding Property:
Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also simple member functions. The main difference between a non-virtual C++ member function and a virtual member function is in the way they are both resolved. A non-virtual C++ member function is resolved during compile time or static binding. Virtual Functions are resolved during run-time or dynamic binding
• Virtual functions are member functions of a class.
• Virtual functions are declared with the keyword virtual
• Virtual function takes a different functionality in the derived class.
Virtual Constructors and Destructors
A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor.
A virtual destructor is one that is declared as virtual in the base class and is used to ensure that destructors are called in the proper order. It is to be remembered that destructors are called in the reverse order of inheritance. If a base class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class destructor is not called. Refer to the code that follows:
#include
class base
{
public:
~base()
{
}
};
class derived : public base
{
public:
~derived()
{
}
};
void main()
{
base *ptr = new derived();
// some code
delete ptr;
}
In this case the type of the pointer would be considered. Hence as the pointer is of type base, the base class destructor would be called but the derived class destructor would not be called at all. The result is memory leak. In order to avoid this, we have to make the destructor virtual in the base class. This is shown in the example below:
class base
{
public:
virtual ~base()
{
}
};
class derived : public base
{
public:
~derived()
{
}
};
void main()
{
base *ptr = new derived();
// some code
delete ptr;
}
Conclusion:
Virtual methods should be used judiciously as they are slow due to the overhead involved in searching the virtual table. They also increase the size of an object of a class by the size of a pointer. The size of a pointer depends on the size of an integer. Note that in DOS based systems the size of a pointer is 2 bytes whereas in UNIX based systems it is 4
Virtual Base Class
class A {
protected:
int x;
}
class B:virtual public A { };
class C:virtual public A { };
class D:public B,public C
{
public:
int example() {
return x;
}
};
In the above example, both Exf1 and Exf2 are created as Virtual base classes by using the keyword virtual. This enables them to share a common subobject of their base class Exforsys. This results in only one copy that the member function example() of Class Training can access the member data x.
What is Pure Virtual Function? Why and when it is used ?
A virtual function that is initialized to zero (0) is
referred to as pure virtual function.It has no body and
hence also known as do-nothing or the dummy function.
Example: virtual void show()=0;
A class containing one or more pure virtual functions is
called an Abstract class, which means an instance of such
class can't be created (but pointer to that class can be
created).We should use pure virtual function if we do not
want to instantiate a class but make it act as a base class
for all the classes that derive from it.An important thing
to note about pure virtual functions is that these
functions must be overridden in all the derived classes
otherwise the compile would flag out an error.
Note :
1) A class that declares or inherits a virtual function is called a polymorphic class.
2) You redefine a virtual member function, like any member function, in any derived class. Suppose you declare a virtual function named f in a class A, and you derive directly or indirectly from A a class named B. If you declare a function named f in class B with the same name and same parameter list as A::f, then B::f is also virtual (regardless whether or not you declare B::f with the virtual keyword) and it overrides A::f. However, if the parameter lists of A::f and B::f are different, A::f and B::f are considered different, B::f does not override A::f, and B::f is not virtual (unless you have declared it with the virtual keyword). Instead B::f hides A::f. The following example demonstrates this:
#include
using namespace std;
struct A {
virtual void f() { cout << "Class A" << endl; }
};
struct B: A {
void f(int) { cout << "Class B" << endl; }
};
struct C: B {
void f() { cout << "Class C" << endl; }
};
int main() {
B b; C c;
A* pa1 = &b;
A* pa2 = &c;
// b.f();
pa1->f();
pa2->f();
}
The following is the output of the above example:
Class A
Class C
covariant virtual function
The return type of an overriding virtual function may differ from the return type of the overridden virtual function. This overriding function would then be called a covariant virtual function. Suppose that B::f overrides the virtual function A::f. The return types of A::f and B::f may differ if all the following conditions are met:
1) The function B::f returns a reference or pointer to a class of type T, and A::f returns a pointer or a reference to an unambiguous direct or indirect base class of T.
class A {
virtual T f(); // f() has a return type T and it is a virtual function
};
class B::public A {
T1 f(); // f() is overridden function from vittual function and having return type of T1.
// Note: T1 mush have to derived from T in direct/ indirect
//Covarient virtual function
};
2) The const or volatile qualification of the pointer or reference returned by B::f has the same or less const or volatile qualification of the pointer or reference returned by A::f.
Note: A::f can be cost and B::f can or can't be const but the reverse will not work.
3) The return type of B::f must be complete at the point of declaration of B::f, or it can be of type B.
The following example demonstrates this:
#include
using namespace std;
struct A { };
class B : private A {
friend class D;
friend class F;
};
A global_A;
B global_B;
struct C {
virtual A* f() {
cout << "A* C::f()" << endl;
return &global_A;
}
};
struct D : C {
B* f() {
cout << "B* D::f()" << endl;
return &global_B;
}
};
struct E;
struct F : C {
// Error:
// E is incomplete
// E* f();
};
struct G : C {
// Error:
// A is an inaccessible base class of B
// B* f();
};
int main() {
D d;
C* cp = &d;
D* dp = &d;
A* ap = cp->f();
B* bp = dp->f();
};
The following is the output of the above example:
B* D::f()
B* D::f()
The statement A* ap = cp->f() calls D::f() and converts the pointer returned to type A*. The statement B* bp = dp->f() calls D::f() as well but does not convert the pointer returned; the type returned is B*. The compiler would not allow the declaration of the virtual function F::f() because E is not a complete class. The compiler would not allow the declaration of the virtual function G::f() because class A is not an accessible base class of B (unlike friend classes D and F, the definition of B does not give access to its members for class G).
CONTD . . .
What is copy constructor ?COPY Constructors
A copy constructor is called whenever a new variable is created from an object.
There are 3 important places where a copy constructor is called.
1. When an object is created from another object of the same type
2. When an object is passed by value as a parameter to a function
3. When an object is returned from a function
Eg:
Person q("Subhransu"); // constructor
Person r(p); // copy constructor is used to build r.
Person p = q; // copy constructor is used to initialize in declaration.
p = q; // Assignment operator, no constructor or copy constructor.
If a copy constructor is not defined in a class, the compiler itself defines one. This will ensure a shallow copy.
According to object are copied Copy constructor can be classified in to two
1. Shallow Copy
class Cents02 | { |
03 | private: |
04 | int m_nCents; |
05 | public: |
06 | Cents(int nCents=0) |
07 | { |
08 | m_nCents = nCents; |
09 | } |
10 | }; |
2. Deep Copy
In a deep copy, the copy operation respects object semantics. For example, copying an object that has a member of type std::string ensures that the corresponding std::string in the target object is copy-constructed by the copy constructor of class std::string.
// Copy constructor02 | MyString::MyString(const MyString& cSource) |
03 | { |
04 | // because m_nLength is not a pointer, we can shallow copy it |
05 | m_nLength = cSource.m_nLength; |
06 |
07 | // m_pchString is a pointer, so we need to deep copy it if it is non-null |
08 | if (cSource.m_pchString) |
09 | { |
10 | // allocate memory for our copy |
11 | m_pchString = new char[m_nLength]; |
12 |
13 | // Copy the string into our newly allocated memory |
14 | strncpy(m_pchString, cSource.m_pchString, m_nLength); |
15 | } |
16 | else |
17 | m_pchString = 0; |
18 | } |
Difference between copy constructor and assignment
A copy constructor is used to initialize a newly declared variable from an existing variable. This makes a deep copy like assignment, but it is somewhat simpler:
1. There is no need to test to see if it is being initialized from itself.
2. There is no need to clean up (eg, delete) an existing value (there is none).
3. A reference to itself is not returned.
inline function vs. #define
- inline function is type checking. If something is invalid, it will let you know at compile time, not at run time.
Upcasting
An object can be used as base type.
// code example of Upcasting
class Base
{
public:
Base(){}
Virtual void foo();
};
class Derived : public Base
{
public:
Derived(){}
void foo() {
cout << "I am in derived "
}
};
Derived* derived_ptr = new Base(); // Upcasting >> macro :
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro.
It expanded during the preprocessing.The main advantage of this faster execution.
It is of two type:
1) Object-like macros
2) function-like macros
1) Object-like macros
An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like because it looks like a data object in code that uses it. They are most commonly used to give symbolic names to numeric constants.
#define BUFFER_SIZE 1024
2) Function-like macro
You can also define macros whose use looks like a function call. These are called function-like macros.
To define a function-like macro,
you use the same `#define' directive, but you put a pair of
parentheses immediately after the macro name. For example,
#define lang_init() c_init()
lang_init()
==> c_init()Function-like macros can take arguments, just like true functions.
Structure padding in C
Structure padding is adding extra bits at the end of the structue,so that the structure completes the word boundary.How structure padding done
Structure Padding is done to do memory alignment. As size of pointer is 4 bytes, if everything is organized by multiple of 4, that it will be easier and faster to calculate the address and processing them. As structures are used to club different size variables, compiler will align to 4 byte boundaries and for that it needs padding.
Structure padding is done by the compilers and this depends on the architectures. Some architectures cannot access the data which will be stored on the odd addresses or they may find difficult to access it. This is the reason for padding extra bytes.
Padding will be done by compiler to structure’s members and to the structure as a whole also. Compiler pads structure as whole because this allows each member of structure aligned in array of structures
Structure padding example
Struct EX
{
Char a;
Short int b;
Char c;
Long d;
};
Due to structure padding this structure size is
12 bytes (a=1 + padding=2 + b=2 + c=1 + padding=3 + d=4) insted of 8 bytes (1+2+1+4).
Packed structures
Some compilers provide #pragma to suppress padding or to make it packed to n number of bytes. Some provide keywords to do this.
#pragma pack(n)
The keyword __attribute__ allows you to specify special attributes of variables or structure fields. This keyword is followed by an attribute specification inside double parentheses
So a packed structure is a structure without padding.
Generally packed structures will be used
• to save space, and
• to format a data structure to transmit over network using some protocol (this is not a good practice of course because you need to deal with endianness).
Structure packing in GCC
The packed attribute specifies that a variable or structure field should have the smallest possible alignment one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.
Here is a structure in which the field x is packed, so that it immediately follows a:
struct foo
{
char a;
int x[2] __attribute__ ((packed));
};
aligned (alignment)
This attribute specifies a minimum alignment for the variable or structure field, measured in bytes. For example, the declaration:
int x __attribute__ ((aligned (16))) = 0;
gcc supports an extension that allows structures or structure members to be marked with __attribute__((packed)), which tells gcc to leave out all padding between members. Sometimes you need this, when you want to make sure of the layout of a structure. For example, you might have something like
struct my_struct {
int field1;
char field2;
} __attribute__((packed));
Without the packed attribute, the struct will have padding between field1 and field2, and that’s no good if this struct is something that has to match hardware or be sent on a wire.
But adding __attribute__((packed)) goes further than just telling gcc that it should not add padding - it also tells gcc that it cannot make any assumptions about the alignment of accesses to structure members. And this leads to disastrously bad code on some architectures.
Boost LibraryA Smart Pointer is a C++ object that acts like a pointer, but additionally deletes the object when it is no longer needed.
shared_ptr pointer to T" using a reference count to determine when the
object is no longer needed. shared_ptr is the generic, most
versatile smart pointer offered by boost.
scoped_ptr a pointer automatically deleted when it goes out of scope.
No assignment possible, but no performance penalties
compared to "raw" pointers
intrusive_ptr another reference counting pointer. It provides better
performance than shared_ptr, but requires the type T to
provide its own reference counting mechanism.
weak_ptr a weak pointer, working in conjunction with shared_ptr to
avoid circular references
shared_array like shared_ptr, but access syntax is for an Array of T
scoped_array like scoped_ptr, but access syntax is for an Array of T
Syntax:
boost::scoped_ptr<CSample> samplePtr(new CSample);
Important Features
shared_ptr<T>works with an incomplete type: When declaring or using ashared_ptr<T>,Tmay be an "incomplete type". E.g., you do only a forward declaration usingclass T;. But do not yet define howTreally looks like. Only where you dereference the pointer, the compiler needs to know "everything".
shared_ptr<T>works with any type: There are virtually no requirements towardsT(such as deriving from a base class).
shared_ptr<T>supports a custom deleter So you can store objects that need a different cleanup thandelete p. For more information, see the boost documentation.
- Implicit conversion: If a type
U *can be implicitly converted toT *(e.g., becauseTis base class ofU), ashared_ptr<U>can also be converted toshared_ptr<T>implicitly.
shared_ptris thread safe (This is a design choice rather than an advantage, however, it is a necessity in multithreaded programs, and the overhead is low.)
Static Library & Dynamic LibraryA library is a package of code that is meant to be reused by many programs.
1) static library :
A static library (also known as an archive) consists of routines that are compiled and linked directly into your program. When you compile a program that uses a static library, all the functionality of the static library becomes part of your executable. On Windows, static libraries typically have a .lib extension, whereas on linux, static libraries typically have an .a (archive) extension. One advantage of static libraries is that you only have to distribute the executable in order for users to run your program. Because the library becomes part of your program, this ensures that the right version of the library is always used with your program. Also, because static libraries become part of your program, you can use them just like functionality you’ve written for your own program. On the downside, because a copy of the library becomes part of every executable that uses it, this can cause a lot of wasted space. Static libraries also can not be upgraded easy — to update the library, the entire executable needs to be replaced.
2) Dynamic Library
A dynamic library (also called a shared library) consists of routines that are loaded into your application at run time. When you compile a program that uses a dynamic library, the library does not become part of your executable — it remains as a separate unit. On Windows, dynamic libraries typically have a .dll (dynamic link library) extension, whereas on Linux, dynamic libraries typically have a .so (shared object) extension. One advantage of dynamic libraries is that many programs can share one copy, which saves space. Perhaps a bigger advantage is that the dynamic library can be upgraded to a newer version without replacing all of the executables that use it.
Because dynamic libraries are not linked into your program, programs using dynamic libraries must explicitly load and interface with the dynamic library. This mechanisms can be confusing, and makes interfacing with a dynamic library awkward. To make dynamic libraries easier to use, an import library can be used.
An import library is a library that automates the process of loading and using a dynamic library. On Windows, this is typically done via a small static library (.lib) of the same name as the dynamic library (.dll). The static library is linked into the program at compile time, and then the functionality of the dynamic library can effectively be used as if it were a static library.