Thursday, July 9, 2009

In C++, Can u explain more abouthow to use inheritance?

I also want to know how to use delete and static_cast%26lt;type%26gt;...

In C++, Can u explain more abouthow to use inheritance?
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 %26lt;%26lt; pS-%26gt;Area %26lt;%26lt; endl;


pS-%26gt;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%26lt;type%26gt; is just like the type casts in C:


Shape *pS = new Box();


Box * pB = static_cast%26lt;Box *%26gt;( 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.


No comments:

Post a Comment