Tuesday, August 24, 2010

C in C++ Code and C++ code in C

extern "C" is understandable by only C++ compiler thats why we generaly wrap it in  # if defs . When same code can be compiled by c compiler also 
only cpp compiler has defined cpluscplus.


#ifdef __cplusplus
 extern "C" {
 #endif



In cpp code if we want a function that will be callable from C program.We need declaration like this
cpp file.

#include 

extern "C" void hello() {
    std::cout << "hello" << '\n';
}

A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded.
C++ compiler uses a technique termed name mangling which incorporates the function name with its signature (list of arguments) in order to create a unique name for it, even in case of overloading (this technique is used both for external function and class member functions).
In order to enforce the compiler to avoid name mangling, a global function has to be declared as extern "C":
extern "C" void f(int); //now the generated name is identical to the one given by the programmer.

How to include non standard C header file in C++ code?
 //C++ code

 extern "C" {
   
// Get declaration for f(int i, char c)
   #include "my-C-code.h"
 }

 int main()
 {
   f(7, 'a');  

   
...
 } 


To make it easier its better to change header file itself .
at top putting
#ifdef __cplusplus
 extern "C" {
 #endif

At end  put
 #ifdef __cplusplus
 }
 #endif


Now it  .h can be included  in cPP simply 
 
 // Get declaration for f(int i, char c, float x)
 #include "my-C-code.h" 


 int main()
 {
   f(7, 'x');     

   
...
 }

--------------
if we dont want to include whole file individual function can be declared 
extern "C" void f(int i, char c); 
Or a group can be :

extern "C" {
   void   f(int i, char c);
   int    f2(char* s, char const* s2);
   double f3(double a, double b);
 }

Tuesday, May 11, 2010

Unexpected Exception

How to specify Exception?
 func()                    // this can throw any Excpeption
 func()  throw()      // this Will NOT throw any Excpeption
 func()  throw (bad_alloc , X )  // this can throw only specified  Excpeption

unexpected() is called when function throws exception other  than specified 

It uses     _unexpected_handler  which can be changed  
unexpected_handler old_hand  = set_unexpected( newfunction);
 
void newfunction( ) 
{
   cout << "Hi" << endl;
   terminate( );
}
 

Sunday, May 9, 2010

Auotmatic Type Conversion and use of Explicit Keyword

1. By Constructor Conversion :
        See this situation .

Output :
Constructor B called
Hi inside Function
--------------------------------------------------------------------------------
Preventing constructor conversion.
This Behaviour of automatic calling of constructor . can be stopped if constructor is explicit.
Explicit Constructor: Constructor with explicit keyword.It prevents compliler from performing implicit (Unexpected) type conversions.


After this   func (a); will not get compiled .

Output:Compliation Fails
auotTypeConversion.cpp: In function `int main()':
auotTypeConversion.cpp:18: error: conversion from `A' to non-scalar type `B' requested

2. Operator Conversion :

OUTPUT:
inside conversion operator B--> A
inside A constructor i=10
Function call

Saturday, May 8, 2010

Exception Handling

Q How to catch all type of Exception ?
Ans Three dots try { } catch(...)
three dots is called   Ellipsis

Friday, May 7, 2010

When to return const refrence ?

a)When do we return by refrence?
Ans:. it avoids copying . But never return reference of local object .
     So that functions can be l-values
     We do this when we want to modify  lvalue  . we do this in operator overlaoding of " ="  to support a=b=c  chaining 
MyClass & operator=(const MyClass &rhs);
MyClass & operator+=(const MyClass &rhs) 
 
b) Returning just const
As const return can be assigned to nonconst variable and changed .
But if function is used in expression then temporary return as it is const will be prohibited .
struct foo
{
void bar() {}
void barfoo() const {}
};

foo foobar1() {return foo();}
const foo foobar2() {return foo();}

int main()
{
foobar1().barfoo(); //perfectly legal, calling const member function of non-const object
foobar1().bar(); //perfectly legal, calling non-const member function of non-const object
foobar2().barfoo(); // perfectly legal, calling const member function of const object
foobar2().bar(); // this willl not compile
}

In operator overloading we use it often to make sure
const MyClass MyClass::operator+(const MyClass &other) const


(a+b)=c // this kind of things will not get compile
We make sure (a+b).func()  is allowed only if func()is const function .
this is called const correectness

c)When to return const refrence
This make lot of sense .


http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

Friday, April 30, 2010

Six important People of C++

Monday, April 26, 2010

Unhandeled Exceptions in C++ terminate

If a Exception is not handled With proper catch Block of same type or  catch(...) is also not there terminate run-time function is called Which calls abort( )   internally .
To Avoid this we can provide our own Termination Handler function  like:

terminate_handler  set_terminate( term_function );
 
This can be  done  any where in the code . BEFORE EXCEPTION IS THROWN.
Also only one Function can be registered for as Handler
_uncaught_handler
Multiple calls of  set_terminate() overwrites previous value.

OUTPUT :
terminate called after throwing an instance of 'char const*'
Aborted
Note : set_terminate is after exception is thrown.

OUTPUT:
Second Handler was called by terminate
Note :first  handler is overwritten

If we throw Derived object will it catch by base or derived ? see code and Answer


Output :
base cought

NEXT Question comes in Mind is  : 
What if inheritance is of PRIVATE or PROTECTED
Ans: in that case object will be cought at Derived catch block only.

Remember : Only Public inheritance is " IS-A "relation ., can be treated as BASE TYPE  

Friday, April 23, 2010

Virtual Function with default Arguments

Can Virtual Functin have default Arguments?
Yes they can bu tthere is a catch here
Remember virtual functions are dynamically bound, but default parameters are statically bound .
Thing is for Runtime efficiency default parameter are not dynamically bounded .



OUTPUT:
der default 4  Passed  5
base default 4  Passed 15

Friday, April 9, 2010

Some CPP certifications

1)Brain Bench, Inc. USA, C++(expert level),
2)Professional Aptitude Council, Inc. California,
C++(advanced):

Thursday, April 8, 2010

Inline Virtual Function

Inline doesn't go with Virtual  . Generally compiler ignores inline directive for virtual function.
Inline has to be done at compile time but Virtual says wait until Run time At compile time compiler doesn't know which function to insert .
 Point    :Virtual function can be inlined if they are called by OBJ (not by pointer ) But we hardly use virtual function without Pointer
   

Some Random C++ question Which I dont want to forget

Q Global object how are the created when?

OUTPUT :
base CTOR
In main
base DTOR
------------------------------------------------------------------------
Q ) Qualifiers availabel in C++ ?
Ans : I always forget mutable , 3 qualifiers are there const ,volatile and mutable .
 What is Mutable .
 Ans :  It specifies  that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

struct data
{
char name[80] ;
mutable int age ;
}
const data person  = { "Amit", 24 };        // Initialisation
strcpy (  person .name, "Sharma");       // compiler error
person.salaray = 2000 ;                         // Allowed since it is mutable
---------------------------------------------------------------------

Q) What problem does the namespace feature solve ?
 http://www.glenmccl.com/ns_comp.htm

Will it core ??? if yes where


My First Answer was yes De-Referencing NULL pointer will core at line 15
This is wrong function is binded to class not an object compiler just checks the TYPE of pointer and calls Func1 Successfully
It cores at line 16 where in function s=0; is done
Thing is as long as no instance attribute is used in the func(), and the method is not virtual   , NULL pointer  need not to be dereferenced.

Tuesday, April 6, 2010

Virtual Inheritance

Well  we all know why it is Required To resolve Diamond Problem
What if  i have a code like this  where class Bsse has no function and derived twice in Diamond way

Output: in Base In Der1 in Base Der 2 Most Derived
Point is until we access any thing common in base class Explicitly there is NO issue
Lets see Accessing any variable from base : Output : Compilation fails  virtual.cpp: In function `int main()':  virtual.cpp:31: error: request for member `Base_a' is ambiguous  virtual.cpp:6: error: candidates are: int Base::Base_a  virtual.cpp:6: error: int Base::Base_a To solve we need Virtual inheritance .   Output : See the Constructor Sequence
in Base
In Der1
Der 2
Most Derived
Accessing  Base_a 0

how to make Singleton Thread safe

Monday, April 5, 2010

Protected Constructor ??

these are used to make abstract class  .
Class who has Protected Constructor  Can 't be instantiated But available to inherit  

Monday, March 29, 2010

Private Virtual Functions ???

Q: If base class has public Virtual function and Derived has private function for same virtual .
Which function is called by base PTR pointing to derived ??
Ans : derived will get call , though it is private at derived
-----------------------------------------------------

----------------------
Output :
./a.out
derv1::f
derv2::f
--------------------------------------------
Q What if I have derived PTR and its pointing to Derived object and i call for VIRtual function??
Ans :  This will not get compiled 
 error: `virtual void der1::f()' is private

Friday, March 26, 2010

Can derived pointer point to base class object ?

Ans: Yes we have to cast it .without cast it will not get compiled .
g++ error: invalid conversion from `base*' to `der1*'
 Remember dynamic_cast will not work (it disallows base to derived casting ). Use Static cast or Reinterpret cast.
Exmaple
 der1* obj1 =  static_cast < der1* > (new base()) ;

Now Question comes in mind what if i call a new function(which is not in Base ) defined in Derived class form this Derived pointer (which is Actually points to Base object ) .

I thought it should not allow But it got compiled and ran successfully .

What if I wand to access public member variable by same Derived pointer (which is Actually points to Base object ) .  Remember derived object is not created . 
i thought it should core dump But its accessing variables and printing Garbage value .
Output : base::print
base::k
der1::nonvirtual :9
value of derived var 8

Operator overloading

Operator Function must be member Function or at least  take one argument of uesr defined type  
To overload operator we have three options .
1) Member Functions : when left hand Operand is of Class type
obj + 2 ; obj1 + obj2 .
This will not work for  3 + obj1
as it will become     3.operator+(obj1)   and    +    is not overloaded for int type.
Any operator function intended to accept first operand as basic type CAN'T be Member function. 

Imp : operator = , [] , -> , () ,->* all these must be Member

2) Global Functions : If we want left hand operand to be of other class type .
Example: >> , << . To support 4 + obj1

3) Friend functions : friend is just provided for global functions to get access
of Private and protected members .

But if we dont have Constructor number(int I = 0) which is imlicitly casting
1 ----> number And letting a + 1; to work.
compilation will fail .
BJARNE recommendation:
1.Operator that inherently modify value of first Argument  should be member fuction. like +=,-= ,*= and all .
   complex & operator+=(complex a) ;
2. Operator that simply produce a new value based on its Arguments  as + ,- ,*, / should defined outside of class.
     complex operator + (const complex & a , const complex & b)
{  complex r = a;
   return r+=b;
}
Q Why cant we overload  :: (Scope )  . (dot )  and  .* (member selection throgh ptr to functoion) ?   
Ans: All of these operator take second argument as name not as value . 
They are used to refer members not to  operate on them.


Q Why  ->  is overloadable and .(dot is not )?

--------------overloading array --------- 
86   
// overloaded subscript operator for non-const Arrays;
87   // reference return creates a modifiable lvalue
88   int &Array::operator[]( int subscript )
89   {
90      // check for subscript out-of-range error
91      if ( subscript < 0 || subscript >= size )
92      {
93         cerr << "\nError: Subscript " << subscript
94            << " out of range" << endl;
95         exit( 1 ); // terminate program; subscript out of range
96      } // end if
97
98      return ptr[ subscript ]; // reference return
99   } // end function operator[]
100
101  // overloaded subscript operator for const Arrays
102  // const reference return creates an rvalue
103  int Array::operator[]( int subscript ) const
104  {
105     // check for subscript out-of-range error
106     if ( subscript < 0 || subscript >= size )
107     {
108        cerr << "\nError: Subscript " << subscript
109           << " out of range" << endl;
110        exit( 1 ); // terminate program; subscript out of range
111     } // end if
112
113     return ptr[ subscript ]; // returns copy of this element
114  } // end function operator[]
 
 
 
LINK :http://www.deitel.com/articles/cplusplus_tutorials/20060204/cplusplus_operatoroverloading_arrayclass_Page3.html 

Friday, February 19, 2010

Inheritance .

In any inheritance Private members are not inherited .

Public Inheritance : things will come as it is , Protect base-->Protected deirved , Public base--> Public derived .

Private Inheritance : Things will come as Private Protected base-->Private deirved , Public base--> Private derived .

Protected Inheritance : Things will come as Protected Protected base -->Protected deirved , Public base--> Protected derived .

Virtual Inheritance : used in multiple and multilevel Inheritance to solve "THe famous Diamond problem "
Link : http://en.wikipedia.org/wiki/Virtual_inheritance

Monday, February 1, 2010

Private Constructor / Destructor In C++ and FINAL Class

Private Constructor : Means object cannot be created . but its useful in Singleton class where we provide on static function(or Friend function) to create Single object .

If Destructor is private class Cant be inherited

FINAL Class : Class which can't be inherited . In Java we have final calss facitlity.
Why is it required ? Lets say we have Class that doesn't have a virtual destructor; it may contain some dynamically allocated object. Now, if anyone inherits a class from it and creates the object of the derived class dynamically, it will Lead to Memory Leak . In this case we would like to finalise the class to avoid this leakage
How to do that ?
1) Making constructor Private . and providing static function for creation .
2) Private Destructor.
As static is there object will be created at heap and needs care while deletion .
How can we make object in stack.
3)better way : make a base class with Consturctor private and make derived class its firend so that it can access private Constructor .
Derive final class virtual public from this base class.
whenever anyone attempts to inherit a class from FinalClass and make an object of it, its constructor tries to call the constructor of Virtual base class. But the constructor of  base is private, so the compiler complains about this and it gives an error during the compilation because your Most derived class is not a friend of Base
Why Virtual derivation  helps here ?
Because of Virtual Inheritance rule :Since the most derived class's ctor needs to directly call the virtual base class's ctor 
If it would have been just public inheritance than derivation from final will be allowed ? because there Most derived constructor will call Final class ctor which will call base class ctor(private) . Here indirect relationship is enough.
In Virtual inheritance most derived class object will have two VPTR both pointing to same object of base class  

point : friendship is not inherited in the drive class
REF:
http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4143

Wednesday, January 27, 2010

Association , Aggregation and Composition

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy.
UML:
An aggregation relationship is indicated by placing a white diamond at the end of the association next to the aggregate class. If B aggregates A, then A is a part of B, but their lifetimes are independent:


Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete.
UML
Composition, on the other hand, is shown by a black diamond on the end of association next to the composite class. If B is composed of A, then B controls the lifetime of A.

Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.
Composition is used for objects that have a HAS-A relationship to each other. A car has-a metal frame, has-an engine, and has-a transmission. A personal computer has-a CPU, a motherboard, and other components.

Compositions:
* Typically use normal member variables
* Can use pointer values if the composition class automatically handles allocation/deallocation
* Responsible for creation/destruction of subclasses

Aggregations:
* Typically use pointer variables that point to an object that lives outside the scope of the aggregate class
* Can use reference values that point to an object that lives outside the scope of the aggregate class
* Not responsible for creating/destroying subclasses

IS_A HAS-A difference
IS-A :Public inheritance Mango is a fruit , I am a man .
is-a (subsumption) is a relationship where one class D is a subclass of another class B (and so B is a superclass of D).
HAS -A : has-a relationship in an object is called a member field of an object. Multiple has-a relationships will combine to form a possessive hierarchy , Composition , Aggregation and association all comes under this But all have different Scope.
Private and Protected Inheritance alsocpmes under HAS-A relationship

REf
http://ootips.org/uml-hasa.html

Sunday, January 10, 2010

Good C++ Questions

* Would you be able to explain why/when base classes should have virtual destructors?
Answer : Only polymorpic( class has any virtual functions ) base class should have Virtual Destructor . C ++ specifies that when a derived class object is deleted through a pointer to a base class with a non-virtual destructor, results are undefined If derived class object pointer is accessed as base class pointer .now delete of that pointer(which points to derived object ) will release in Partial free i.e only base object will destroy and derived part will remain as it is . Virtual Destructor ensures proper calling of destructor
Putting virtual Destructor in nonpolymorphic class is an overhead as it will increase Size of every OBJ by 4 byte by inserting VPTR.
* Would you be able to differentiate between inheritance of interface and inheritance of implementation?
Answer: Derivation of Pure virtual function is inheritance of interface Pure virtual funtion will have no implemetation . and derived can implement it on their own . it only derives the interface
Derivation of Simple Member function is inheritance of implementation As derived calss will have same implemetatin of the function as it was in Base class .

* What sorting algorithms do you know? How fast are they?
Answer: I know Merge sort ,Bubble sort ,Quick Sort ,BST (Binary search tree ),
BST is best O(logn). But choice os soritng Algo depends on data size/data pattern also .

* What is "placement new" and why/when would You use it?
Answer: New gets Memory From Heap. But with Placement option we can provide A pre Allocated memory location to save object.
We Use it to void Mem allocation fail which is very rare . It is more used in making Memory pool . It Improves Performance also .

* Should a destructor throw an exception when it detects a problem?
Answer: 1) Destructor Should not throw an error . As Some time Destructor are called in an error scenario
In an Exception Handling from throw(obj) to catch all frames are deallocated automatically Which is called stack Unwinding All local Objs Destructor are called automatically at that point of time if any of the distructor will throw an error . Than its an problem to go to catch or process the thrown error So terminate got called and the whole program will exit

2) If there is and Array of pbjects and all have to dellaocate one by one .
If one in begining will throw an error How others destructor will get called This behaviour is undefined in C++ .
Thing is Destructor should Swallow the Exception in themselves .

* Can you explain the difference between "operator new" and "new operator"?
Answer: new operator is used for Memory allocation and it calls constructor also for .
operator new : Is actual function which only allocates memory Its Prototype is < void* operator (size_t) > , it can be overloaded .

* Where in a hierarchy should you use virtual inheritance?
Answer : In Multiple Inheritance If we know that at some level of inheritance Diamond problem ( A-->B A--->C and B,C-->D now D will have two instance of A) can arise.
To avoid the ambiguity of base object . Virtual Inheritance is required at first level i.e ( A virtual-->B A virtual --->C)

* How can you reseat a reference to make it refer to a different object?
Answer : Its not Allowed. REfrence cannot refer to new OBJECT (address) unlike a pointer.
We can understand like this Reference is a Const Pointer .
int d = 20;
int * const pref = &d ;
now pref++ is not allowed
*pref = 40 ; //is allowed ,pref cant point to any new location.
I hope we understand Diffrence between const pointer and pointer to const .
link : http://blog.voidnish.com/?p=37
Can we overload a Function by changing return type ?
Ans : No Changing of return type is ot considered as change in Function Signature
The C++ compiler identifies a function by its signature (function signature). The function signature is broken down into the following components in that order.

return type ,function label or name and parameters list

The parameter list is further defined as parameter label or name. If the order of the parameters (datatype name) changes even if the function name/label does not change the signature is considered unique. So in C++ it is conceivable to have many different functions/methods with exact same label name (for example Function1) so long as the entire signature is considered unique. So changing the number of parameters their data types the order of them or any combination of these can change the function signature.
Important Note: Changing the return type ALONE is NOT considered change in signature.

Followers