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
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
Wednesday, January 27, 2010
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
Wednesday, December 16, 2009
Static Variable
In C,
A variable declared as static in a function is initialized once, and retains its value between function calls.
It is saved in Data section,
The default initial value of an uninitialized static variable is zero.
If a function or global variable is declared static, it can only be accessed in that file. IT Limits the scope to that file
In C++
Static member variable have only one copy per class Unlike other member variable which have Unique copies for every Object .We cannot initialize the static class member inside of the class.We cannot even initialize the static variable inside of the header file.
in .cpp we need to initialised it like this :
classname : : var_name = 0;
Static Functions are again independent of objects .
Main feature is "this" pointer is not passed to static functions because of that
1) A static member function Can't access NON STATIC MEMBERS can only access static member data
2)A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual
3) Can't be declared const and volatile too.
4) Doesn't need Object to invoke .However if required can be invoked through object on need basis ,
A variable declared as static in a function is initialized once, and retains its value between function calls.
It is saved in Data section,
The default initial value of an uninitialized static variable is zero.
If a function or global variable is declared static, it can only be accessed in that file. IT Limits the scope to that file
In C++
Static member variable have only one copy per class Unlike other member variable which have Unique copies for every Object .We cannot initialize the static class member inside of the class.We cannot even initialize the static variable inside of the header file.
in .cpp we need to initialised it like this :
Static Functions are again independent of objects .
1) A static member function Can't access NON STATIC MEMBERS can only access static member data
2)A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual
3) Can't be declared const and volatile too.
Labels:
Static
Monday, December 14, 2009
Casting : Static , Dynamic, Reinterpret and Const cast
1) dynamic_cast :
Downcast : cast of Base object to Derived Object is Not Allowed .
PS : It is Applicable only for Polymorphic classes.
Q : What will happen when dynamic_cast is applied to a null pointer?
Q Where is type_info (RTTI) is saved
Ans VTABLE has a pointer (at begining ) pointing to type_info struct
2) Static_cast :
Wider than Dynamic (b2d : base to Derived , d2b : Derived to Base)
allows all d2b and b2d both Only condition is Pointer should be compatible type .
Pragremmer has to ensure result if b2d case if Pointer is Derefrenced ????
3) reinterpret_cast:
More wider than Static_cast :
anything to anything cast is allowed . Just do a memcpy bit by bit .
two reinterpret_cast s yields to same object as it was .
Example :
OUTPUT:
./a.out
Null pointer on second base to der DOWNCAST
- It has a Run-time check Based on Run-Time Type Information (RTTI) Information type_info to keep track of dynamic types.Quite heavy ...
- It ensures that Result object will have all valid Data.
Downcast : cast of Base object to Derived Object is Not Allowed .
- When dynamic_cast cannot cast a pointer because it is not a complete object of the required class it returns a null pointer to indicate the failure.
- If dynamic_cast is used to convert to a reference type and the conversion is not possible, an exception of type bad_cast is thrown . As NULL assignment for Reference is not possible .
PS : It is Applicable only for Polymorphic classes.
Q : What will happen when dynamic_cast is applied to a null pointer?
Ans : It throws bad_typeid exception.
Q Where is type_info (RTTI) is saved
Ans VTABLE has a pointer (at begining ) pointing to type_info struct
2) Static_cast :
Wider than Dynamic (b2d : base to Derived , d2b : Derived to Base)
allows all d2b and b2d both Only condition is Pointer should be compatible type .
Pragremmer has to ensure result if b2d case if Pointer is Derefrenced ????
3) reinterpret_cast:
More wider than Static_cast :
anything to anything cast is allowed . Just do a memcpy bit by bit .
two reinterpret_cast s yields to same object as it was .
4) const_cast :
It changes the constness. Can remove or add constness for a variable .If we have to pass a const variable in Function who expects non-const it can be used. To make it mutableExample :
OUTPUT:
./a.out
Null pointer on second base to der DOWNCAST
Labels:
casting dybamic static
Diffrence B/W delete and delete[]
Overview: delete is a operator in C++ , which can be overloaded .
What it does ??
IT frees the Dynamically Allocated Memory pointed by pointer and also calls Destructor for same pointer type .
Example :
*ptr=new ;
delete ptr; // frees and call desturctor also
delete [] is to free dynamically allocated Array , It also calls Destructor for all the objects contained by Array .It is used in conjunction of new[].
Example:
* ptr = new (10); //pointer to an array of 10 obj
then to free memory equal to 10 obj
delete []ptr;
NOTE: One can free the memory even by "delete ptr ;" But it
will free only the first element in Array memory.other Nine will stay as it is .
Also Desructor for the first Element will be called for sure .
Example
employee *arptr = new employee[3];
for (int j = 0 ;j < 3 ;j++)
{
arptr[j].setvalue(j);
}
//delete [] arptr; // frees and call all Dtors employee
* cloneptr = arptr;
delete arptr; // only delets First location and call Dtor for First obj
cloneptr++;
cloneptr->gt;show(); // works fine able to see Variable of 2 nd OBJ NO core dumps
Verdict : This calling delete for array has different behaviour as per implementation some times it corrupts HEAP and some time it jus call one destructor and free First Element .
------------------------------------------------------------------------------------
FAQ on new and Delete
Q what if we delete a ptr pointing to NULL?
No issues safe
Q What if we call delete twice for same pointer ?
This is catastrophic .
Q What is Placement new and placement delete .
Q Why after Placement delete we need to call Destructor Explicilly?
What it does ??
IT frees the Dynamically Allocated Memory pointed by pointer and also calls Destructor for same pointer type .
Example :
delete ptr; // frees and call desturctor also
delete [] is to free dynamically allocated Array , It also calls Destructor for all the objects contained by Array .It is used in conjunction of new[].
Example:
then to free memory equal to 10 obj
delete []ptr;
NOTE: One can free the memory even by "delete ptr ;" But it
will free only the first element in Array memory.other Nine will stay as it is .
Also Desructor for the first Element will be called for sure .
employee *arptr = new employee[3];
for (int j = 0 ;j < 3 ;j++)
Labels:
difference delete delete[]
Subscribe to:
Posts (Atom)
