"Webster" <no***@nowhere.net> wrote in message
news:6q*********************@news04.bloor.is.net.c able.rogers.com...
Hello,
I want to create a Shape class and some subclasses such as Rectangle,
Circle etc. However for the Shape Class, I want to have a list of points (using a
vector) and also I want it so that the Shape Classes forces the subclasses
to implement a Draw() function. I believe what I want is called an
interface right?? If so, how do I go about creating the Shape Class to
force the subclasses to implement the Draw() function??
Thanks for any help!
--
Regards,
Webster
An abstract or pure virtual base class is the same thing AFAIK, and what
this means is a class that cannot be instantiated i.e: it is designed in
such a way that is is only meant to be derived from. These are called
Interfaces in COM, C# etc (dunno about Java).
Note: classes of this type are also know as ADT's ( Abstract data types).
However what you seem to require is a virtual method, which is normally
closely related with ADT's ( Abstract data types) as an ADT which exposes
any methods will normall use vitual methods.
What virtual means is tell the compiler that I intend to overide this
function in a derived class i.e:
class Class1{
public:
virtual void Draw(){std::cout << "Class1 draw()"<< std::endl;}
};
That is an example of a virtual method.
Next if you create a derived class an incorporate a method with the same
signature like so:
class Class2:public Class1{
public:
void Draw(){std::cout << "Class2 draw()"<< std::endl;}
};
When you create an instance of the derived class the compiler knows to call
the correct method i.e:
int main(){
Class1 obj1;
Class2 obj2;
obj1.Draw(); //outputs Class1 Draw()
obj2.Draw(); //outputs Class2 Draw()
return 0;
}
If a function is virtual then it will percolate up to a derived class if the
derived class contains a method of the same signature.
I'm not sure if I have explained this very well but I hope it helps.
You can also create instances of the base class, you don't need to make it
an ADT.
Additionally if you do want to make a base class an ADT then you put '=0'
after one of the methods. The following code would make Class1 pure virtual
and therefore you would be intending that it is not directly initialised and
only to be used as an interface. (This is what lies at the heart of COM and
ATL(Abstract template library) ):
class Class1{
public:
virtual void Draw() =0 {std::cout << "Class1 draw()"<< std::endl;}
};
You cannot create an instance of Class1 now but Class2 can still derive from
it and the virtual functions will still percolate up to Class2. Be sure to
include virtual destructors etc.
However having said that you can declare a pointer to an ADT. It all gets a
bit complicated from here so I'll leave it at that.