constructors and destructors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | /******************************************************* * MYCPLUS Sample Code - https://www.mycplus.com * * * * This code is made available as a service to our * * visitors and is provided strictly for the * * purpose of illustration. * * * * Please direct all inquiries to saqib at mycplus.com * *******************************************************/ #include <iostream.h> class rectangle { // A simple class int height; int width; public: rectangle(void); // with a constuctor, int area(void); // two methods, void initialize(int, int); ~rectangle(void); // and a destructor }; rectangle::rectangle(void) // constuctor { height = 6; width = 6; } int rectangle::area(void) //Area of a rectangle { return height * width; } void rectangle::initialize(int init_height, int init_width) { height = init_height; width = init_width; } rectangle::~rectangle(void) // destructor { height = 0; width = 0; } struct pole { int length; int depth; }; main() { rectangle box, square; pole flag_pole; cout << "The area of the box is " << box.area() << "\n"; cout << "The area of the square is " << square.area() << "\n"; // box.height = 12; // box.width = 10; // square.height = square.width = 8; box.initialize(12, 10); square.initialize(8, 8); flag_pole.length = 50; flag_pole.depth = 6; cout << "The area of the box is " << box.area() << "\n"; cout << "The area of the square is " << square.area() << "\n"; // cout << "The funny area is " << // area(square.height, box.width) << "\n"; // cout << "The bad area is " << // area(square.height, flag_pole.depth) << "\n"; } // Result of execution // // The area of the box is 36 // The area of the square is 36 // The area of the box is 120 // The area of the square is 64 |