list of polymorphic objects

Posted by LivingThing on Stack Overflow See other posts from Stack Overflow or by LivingThing
Published on 2012-02-11T16:07:44Z Indexed on 2013/11/08 9:55 UTC
Read the original article Hit count: 317

Filed under:
|
|
|
|

I have a particular scenario below. The code below should print 'say()' function of B and C class and print 'B says..' and 'C says...' but it doesn't .Any ideas.. I am learning polymorphism so also have commented few questions related to it on the lines of code below.

class A
{
public:
// A() {}
virtual void say() { std::cout << "Said IT ! " << std::endl; }
virtual ~A(); //why virtual destructor ?
 };

void methodCall() // does it matters if the inherited class from A is in this method
{

class B : public A{
public:
//  virtual ~B(); //significance of virtual destructor in 'child' class
virtual void say () // does the overrided method also has to be have the keyword  'virtual'
{ cout << "B Sayssss.... " << endl; }
};
class C : public A{
public:
//virtual ~C();
virtual void say () { cout << "C Says " << endl; }
};

list<A> listOfAs;
list<A>::iterator it;

# 1st scenario
B bObj; 
C cObj;
A *aB = &bObj;
A *aC = &cObj;

# 2nd scenario
//  A aA;
//  B *Ba = &aA;
//  C *Ca = &aA; // I am declaring the objects as in 1st scenario but how about 2nd   scenario, is this suppose to work too?

listOfAs.insert(it,*aB);
listOfAs.insert(it,*aC);

for (it=listOfAs.begin(); it!=listOfAs.end(); it++)
{
cout <<  *it.say()  << endl;
}
}

int main()
{
methodCall();
retrun 0;
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about list