mardi 2 octobre 2012

A Simple polymorphism example...

It seems that the term "Polymorphism" is not so clear that it should to some of team member (and sometimes it also a mess to me to understand object design we made !!!)... So every time, every time i will use polymorphism in my own work, i will try to extract a demonstration/example.

Let's start with the following example in which we can show that we can define a function to call the f function of a 'Base' object, but accessing finally the f function implemented by the child....


class A
{
public:
  virtual void f()
  {
    std::cout << "A::f()" <<std::endl;
  }
};

class B : public A
{
public:
  virtual void f()
  {
    std::cout << "B::f()" << std::endl;
  }
};

class AI : public A
{

};

class BI : public B
{

};

void master_f(A& base_ref)
{
  base_ref.f();
}

int _tmain(int argc, _TCHAR* argv[])
{
  AI oAI;
  BI oBI;

  master_f(oAI);
  master_f(oBI);

 return 0;
}

Aucun commentaire :

Enregistrer un commentaire