The C++ dynamically allocated class object program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using pointer to objects to dynamically allocate class object in C++ programming
To show: How to dynamically allocated object using pointer variable, new and delete keywords in C++ programming
// C++ dynamically allocated class object using pointer to an object
#include <iostream>
using namespace std;
// class declaration
class wall
{
// two private member variables
int length;
int width;
public:
// constructor
wall(void);
// two methods
void set(int new_length, int new_width);
int get_area(void);
};
// class implementation part
// constructor
wall::wall(void)
{
// just provide the initial value to the objects
length = 8;
width = 8;
}
// this method will set a wall size to the input parameters
void wall::set(int new_length, int new_width)
{
length = new_length;
width = new_width;
}
// this method will calculate and return the area of the wall instance
int wall::get_area(void)
{
return (length * width);
}
// the main program
void main(void)
{
// objects are instantiated of type wall class
wall small, medium, large;
// a pointer to wall class object
wall *point;
// overriding the default/constructor values for small and large
small.set(5, 7);
large.set(15, 20);
// use the defaults value supplied by the constructor for this new object instantiation pointed by point pointer
point = new wall;
cout<<"Use small.set(5, 7): ";
cout<<"Area of the small wall surface is "<<small.get_area()<<endl<<endl;
cout<<"Use default/constructor value medium.set(8, 8): ";
cout<<"Area of the medium wall surface is "<<medium.get_area()<<endl<<endl;
cout<<"Use large.set(15, 20): ";
cout<<"Area of the large wall surface is "<<large.get_area()<<endl<<endl;
cout<<"Use default/constructor value, point->get_area(): ";
cout<<"New surface area of wall "<<point->get_area()<<endl<<endl;
cout<<"Use new value, point->set(12, 12): ";
// new value override the constructor
point->set(12, 12);
cout<<"New surface area of wall "<<point->get_area()<<endl<<endl;
delete point;
point = NULL;
return;
}
Output example:
Use small.set(5, 7): Area of the small wall surface is 35
Use default/constructor value medium.set(8, 8): Area of the medium wall surface is 64
Use large.set(15, 20): Area of the large wall surface is 300
Use default/constructor value, point->get_area(): New surface area of wall 64
Use new value, point->set(12, 12): New surface area of wall 144
Press any key to continue . . .