Thursday, April 8, 2010

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 

Followers