English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I also want to know how to use delete and static_cast...

2007-11-07 03:42:18 · 1 answers · asked by David Junior 3 in Computers & Internet Programming & Design

1 answers

Inheritance is used to put common features of objects into a base class. The class example is if you have a Shape base class and Box and Circle derived classes. The Shape class would could virtual functions to report the area and circumference of the shape and another to draw the shape. The Box and Circle classes implement these functions.

class Shape { // a sample virtual base class
public:
// These are pure virtual. There is no Shape::Area function.
virtual double Area( void ) const = 0;
virtual double Circumference( void ) const = 0;
virtual void Draw( Window * p ) const = 0;
};
class Box : public Shape { // a sample derived class
double x1, y1, x2, y2;
public:
Box( void );
virtual double Area( void ) const;
virtual double Circumference( void ) const;
virtual void Draw( Window * p ) const;
}

double Box::Area( void ) const {
return ( x2 - x1 ) * ( y2 - y1 ); }

Then you can use a Box object through a Shape pointer:
Shape * pS = new Box();
cout << pS->Area << endl;
pS->Draw( pWnd );

Using new and delete. You use these similarly to how you use malloc and free, except that new and delete are specific to a class. I just used new above. It allocates the space needed by a Box object, then calls the Box constructor function. Some time later, the object should be deleted or it will be a memory leak:
delete pS;
New and delete can also be used to work with arrays:
int * pInts = new int[100];
int * pBoxes = new Box[100];
Only the default constructor Box( void ) can be used for an array allocation. When you delete the array, you have to use the array delete:
delete [] pInts;
delete [] pBoxes;
Always use the proper version of delete that matches the new or the objects don't get destroyed properly.

Using static_cast is just like the type casts in C:
Shape *pS = new Box();
Box * pB = static_cast( pS );
There's no type checking involved with a static_cast. In this example, the pointers will point to the exact same memory location, even if that isn't really the proper thing to do when casting a Shape pointer to a Box pointer.

2007-11-07 03:45:28 · answer #1 · answered by Neebler 5 · 0 0

fedest.com, questions and answers