Cognzant Technology Solutions Interview Question
Software AnalystsTeam: Embedded
Country: United States
Interview Type: In-Person
Static objects can be determined as follows:
- Place the counter variable in constructor( it increments the objects for both static and dynamic)
- Subtract the dynamically allocated objects count
For example:
I created 10 static and 20 dynamic
then the counter = 30 ( as per constructor)
Subtract dynamic counter from counter gives you the number of static objects
Static = Counter - Dynamic Obj
Dynamic = will be determined by operator overloading
make a static Counter and increment it in all constructors even in copy constructor also so this will tell total no of objects now u need to override new new[] and placement version also and make a dynamic counter here also static type so this will tell u dynamic objects and if u subtract it from total object then u can get static objects
Create two static variables in the class. say stat_count and dyn_count
Increment the stat_count in the constructor you use to create instance of your class variables.
Increment the dyn_count in the overloaded new operator.
now static objects is equal to (stat_count - dyn_count)
and dynamic objects is equal to dyn_count.
- For counting dynamically created objects we can use operator overloading technique
- Rajesh Manem November 20, 2013void * operator new(size_t sz)
{
// create the object
// increment the number of objects
}
similarly we have to use operator delete to know exactly the number of objects are alive.
I am not sure about to find the static number of objects. Generally we can use static counter to determine the number of objects(includes both static and dynamic).