2013年2月1日 星期五

Concrete Class vs. Abstract Class

Abstract Class

An abstract class is a class for which one or more methods are declared but not defined, meaning that the compiler knows these methods are part of the class, but not what code to execute for that method.

Eg.
 class shape  
 {  
 public:  
  virtual void draw() = 0;  
 };  

You cannot instantiate this class because it is abstract, after all, the compiler wouldn't know what code to execute if you called member draw.


Concrete Class

A class that has any abstract methods is abstract, any class that doesn't is concrete.

Eg.
 class circle : public shape {  
 public:  
  circle(int x, int y, int radius) {  
   /* set up the circle */  
  }  
  void draw() {  
   /* do stuff to draw the circle */  
  }  
 };  
 class rectangle : public shape {  
 public:  
  rectangle(int min_x, int min_y, int max_x, int max_y) {  
   /* set up rectangle */  
  }  
  void draw() {  
   /* do stuff to draw the rectangle */  
  }  
 };  

Now you can instantiate the concrete objects circle and rectangle and use their draw methods:

Eg.
 circle my_circle(40, 30, 10);  
 rectangle my_rectangle(20, 10, 50, 15);  
 my_circle.draw();  
 my_rectangle.draw();  


Question 1: Why would you want to do this?

Ans: To take advantage of the inheritance

Eg.
 std::vector<shape*> my_scene;  
 my_scene.push_back(new circle(40, 30, 10));  
 my_scene.push_back(new rectangle(20, 10, 50, 15));  


Question 2: Why the draw function of shape is abstract, and not just an empty function?

Ans: We don't want objects of type shape, they wouldn't be real things anyway. So it doesn't make sense to define an implementation for the draw method. Making the shape class abstract prevents us from mistakenly instantiating the shape class, or mistakenly calling the empty draw function of the base class instead of the draw function of the derived classes.

--

ref. http://stackoverflow.com/questions/2149207/what-is-the-difference-between-a-concrete-class-and-an-abstract-class

沒有留言:

張貼留言