Dynamic Object – Object Oriented Programming (OOP)

Download our Android App from Google Play Store and start reading Reference Notes Offline.

Dynamic objectDynamic Object – Reference Note
Object Oriented Programming (OOP)
Third Semester | Second year
BSc.CSIT | Tribhuvan University (TU)

Dynamic object
Dynamic objects are those type of objects whose lifetime may be controlled by a particular scope. It is used when object to be created is not predictable enough. When we can’t determine object identities, quantities, lifetimes at compile time we use dynamic objects. When creating dynamic objects, they cannot be given unique names so we have to give them some other identities i.e; using pointers. The memory for dynamic objects is allocated in the heap rather than stack.

Creating dynamic object

  • Dynamic objects use dynamic memory allocation.
  • Pointers can be directed to an area of dynamically allocated memory at runtime. This can be then made to point the object.

Point2d *point;
point = new Point2D();

  • new keyword is used to allocate required memory for object.
  • To send messages or use methods, we use ‘->’ operator.

i.e cout<point->gety();

Destroying dynamic objects

  • Dynamic objects are destroyed by calling the destructor either by the programmer or by the program when the object falls out of scope.
  • delete keyword is used to deallocate memory

i.e delete point;

Now, let’s see one example
#include<iostream.h>
class Point2D
{
int x, y;
public:
int getx(); {
return x;
}
int gety(){
return y;
}
Point2D(){
x = 0;
y = 0;
}
};
void main(){
point2D *point;
point = new Point2D();
cout<point->getx();
cout<point->gety();
delete point;
}

(Visited 995 times, 1 visits today)

Posted By : Digvijay | Comment RSS | Category : Third Semester
Tag : ,

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

Wordpress DMCA
Community | Toolbar | Android App | Founder/Developer : Hari Prasad Chaudhary | CSIT Portal Manager : Digvijay Chaudhary