C++ 43: Creating Objects Dynamically
Pointer and Object:
if required we can store address of an object in the pointer
Syntax: class_name *ptr_name = & object_name;
Accessing object members by using pointer:
If the pointer is pointing to an objetct then the members of the object can be access by using following way:
Syntax:
1) ptr_name = member_name
2) (*ptr_name)member_name
Example:
//Pointer and Object#include <iostream>#include <string.h>using namespace std;class Student{private:int RN;char N[20], D[20];public:Student(int rn, char n[], char d[]){RN = rn;strcpy(N, n);strcpy(D, d);}void showData(){cout << "Roll No: " << RN << endl;cout << "Name: " << N << endl;cout << "Department: " << D << endl;}};int main(){Student a(111, "Jack", "CSE");Student *p;p = &a;// pointer to object(*p).showData();p->showData();return 0;}
Output:
Roll No: 111
Name: Jack
Department: CSE
Roll No: 111
Name: Jack
Department: CSECreating objects dynamically / Dynamic Initialization of object / Pointer to object
- The object is created dynamically then, we can destroy the object at runtime if the object is no more required.
- The object can be create and dynamically as follows:
To create object dynamically- class_name *ptr_name = new class_name(val 1,val2, ...);
To destroy object dynymically - delete ptr_name;
#include <iostream>#include <string.h>
using namespace std;
class Student{private: int RN; char N[20], D[20];
public: Student(int rn, char n[], char d[]) { RN = rn; strcpy(N, n); strcpy(D, d); } void showData() { cout << "Roll No: " << RN << endl; cout << "Name: " << N << endl; cout << "Department: " << D << endl; }};
int main(){ // Student a(111, "Jack", "CSE"); // a.showData();
// Student b(112, "JAmes", "IT"); // b.shoeData();
// Student c(113, "William", "CSE"); // c.showData();
Student *p = new Student(111, "Jack", "CSE"); //Reserving mrmory p->showData(); delete p; //Relesing memory p = new Student(112, "James", "IT"); //Reserving mrmory p->showData(); delete p; //Relesing memory return 0;}Output:
Roll No: 111
Name: Jack
Department: CSE
Roll No: 112
Name: James
Department: IT
Comments
Post a Comment