ABSTRACT CLASSES An abstract class is a class with at least one

advertisement
ABSTRACT CLASSES
An abstract class is a class with at least one pure virtual function. A
virtual function is specified as pure by setting it equal to zero. An
abstract class can be used as a base class for other classes. No objects
of an abstract classes can be created. An abstract class cannot be used
as an argument type or as a function return type. However, you can
declare pointers to an abstract classes.
References to an abstract class are allowed, provided that a temporary
objects is not needed in initialization. For example:
Class shape {
//abstract class
Pointer center;
.
.
.
public:
where() { return center; }
move( point p) { center = p; draw(); }
virtual void rotate( int ) = 0;
virtual void draw() = 0;
virtual void hilite() = 0;
.
.
.
}
//pure virtual function
//pure virtual function
//pure virtual function
shape x; //ERROR: attempt to create an object of an abstract class
shape *sptr; //pointer to abstract class OK!
shape f(); //ERROR: abstract class cannot be a returned type
int g( shape s ); //ERROR: abstract class cannot be a function argument
type
shape &h(shape &); //reference to abstract class as return value or
function
//argument is OK!
Suppose that D is a derived class with the abstract class B as its
immediate base class Then for each pure virtual function pvf in B, if D
doesn't provide a definition for pvf, pvf becomes a pure member function
of D, and D will also be an abstract class.
For example, using the class shape previously outlined:
Class circle : public shape { //circle derived from abstract class
int radius; //private
public:
void(int) { } //virtual function defined: no action
// to rotate a circle
void draw(); //circle::draw must be defined somewhere!
}
Member functions can be called from a constructor of an abstract class,
but calling a pure virtual function directly or indirectly from such a
constructor provokes a run-time error.
Download