these are used to make abstract class .
Class who has Protected Constructor Can 't be instantiated But available to inherit
This blog is created to improve CPP and OOPS concept . It include OOPS concept , CPP FAQ , CPP Interview questions and many helpful material to improve CPP
Monday, April 5, 2010
Friday, April 2, 2010
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
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
Labels:
Virtual
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
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 .
{ 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 )?
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
Labels:
operatorOverloading
Thursday, March 18, 2010
STL related stuff
http://www.sgi.com/tech/stl/stl_introduction.html
STL FAQ
http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html#containers2
container adaptors (stack, queue, priority_queue) have no iterators.
STL FAQ
http://www.halpernwightsoftware.com/stdlib-scratch/quickref.html#containers2
container adaptors (stack, queue, priority_queue) have no iterators.
Labels:
STL
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
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
Labels:
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
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
Labels:
Final class
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
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
Labels:
Agg Comp Association
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.
Labels:
FAQ
Subscribe to:
Posts (Atom)