Posted: Sun Jul 13, 2003 1:42 am Post subject: [tutorial] Inheritance & Polymorphism
In inheritance and polymorphism are two major components of OOP
Ill start by covering inheritance (briefly)
Inheritance can be characterized by "is a". If classB inherits from classA, classB is a classA. This means that all of the functions and variables in classA are also part of classB. The new class adds its own unique functions and data while retaining the old info from classA. This avoids repition of code
example:
code:
class Animal
{
public:
int idnum;
void Procreate(){}
};
class Dog:public Animal
{
public:
int dogtag;
void Run(){}
};
class Bird:public Animal
{
public:
void Fly(){}
};
Polymorphism is closely related to inheritance. There different types of polymorphism. They include operator overloading, and function overloading. The type that deals with inheritance is very useful.
Polymorphism is when a function in a derived class overides a function in the base class. To do this the function should have the word virtual in front of it (it can be done without it but it is less proper). The virtual function from the base class is redefined without the virtual keyword in the derived classes.
for example
code:
class Animal
{
public:
int idnum;
virtual void Move()
{ //generic move
}
};
class Dog:public Animal
{
public:
int dogtag;
void Move()
{//the dog runs
This may not seem very useful at the moment. But the virtual functions of the derived objects can be accesed using a pointer to the base class (only the common functions and data can be accessed)
to illustrate
code:
Animal *fido=new Dog;
Animal *tweet=new Bird;
fido->Move();
tweet->Move();
in some cases the virtual function need not be defined in the base class. In this case the class can be declared as abstract. This occurs when it has one or more abstract functions (alt: pure virtual functions)
an abstract function is declared as so
code:
virtual void mycode()=0;
This has been an intro to polymorphism and inheritance. If u gave anything to add just post.
Sponsor Sponsor
SilverSprite
Posted: Sun Jul 13, 2003 3:21 am Post subject: (No subject)
how about subsubclasses? possible?
Tony
Posted: Sun Jul 13, 2003 3:29 am Post subject: (No subject)
I'd assume so... Just inherit a class that inherits another class already
code:
class Animal
{
public:
int idnum;
void Procreate(){}
};
class Dog:public Animal
{
public:
int dogtag;
void Run(){}
};
class Poodle:public Dog
{
public:
char[30] name;
};
Poodle is a subclass of a Dog and still inherits properties of Animal (since dog is an animal)