Skip to main content

Posts

Showing posts from February, 2018

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t

RTTI

Oh, do not confuse this word with RTI - right to information. This is not a political blog :). RTTI - run time type identification is a concept in C++, which gives the type of the object during run time. But it can be used only with polymorphic classes - i.e. the classes which have at least one virtual function. Typeid typeid is an operator in C++ which gives the actual type of the object. So what is actual type of object? Is it different from the one we have defined it with? It may be. class A { public: virtual void print(){} }; class B : public A { }; int main () { int a; A obj1; B obj2; A * ptr1 = new B; }  In the code above, type of a is integer. Type of obj1 is A. Type of obj2 is B. But what about *ptr1? Is the type of *ptr1 A or B? typeid operator correctly gives its type as B. Note : We have added a dummy print function in base class, to make A as polymorphic. Now let us use typeid operator - which needs the inclusion of head

Polymorphism

You hear the term Polymorphism too frequently with object oriented languages. Along with Inheritance and Encapsulation, polymorphism is one of the corner stones of object oriented design. What is Polymorphism, exactly? Polymorphism is a mechanism by which you provide single interface for multiple methods. (poly - many, morph - form). In C++, polymorphism can be compile time or run-time. Compile time polymorphism is provided with the help of overloaded operators/functions and templates. Run time polymorphism is provided with the help of virtual functions and late binding. Late Binding: Connecting a function call to function body is called binding. Most functions use early binding where this binding happens before the program is run - during compile time. This is also called static binding. Late binding (also called dynamic binding)  is when a function call is connected to function body at run time. This is done after looking at the type of the object. Late binding is ach