View Full Version : Inheritance and Polymorphism


S.Tarafdar
08-24-03, 03:52 AM
I have this code:

#include&ltiostream&gt
#include&ltstring&gt
using namespace std;

class A{
protected:
int counter;
void printhelper(string name) const{
cout&lt&ltname&lt&lt":"&lt&ltcounter&lt&ltendl;
}

public:
A(){
counter=0;
}
void action(){
counter++;
print();
}

virtual void print() const{
printhelper("A");
}
};

class B:public A{
public:
virtual void print() const{
printhelper("B");
}
};

class C:public A{
public:
void action (){
counter--;
print();
}

virtual void print() const{
printhelper("C");
}
};

int main(){
A a;
a.action();
B b;
b.action();b.action();
C c; c.action();
A *list[]={&a,&b,&c};

for (int i=0 ;i&lt3;i++){
list[i]-&gtaction();
}

return 0;
}


And the output of the program is:
A:1
B:1
B:2
C:-1
A:2
B:3
C:0
My question is about the last output:C:0
why is it not C:-2?


Pls help.
Thanks,
S.Tarafdar

okinrus
08-24-03, 04:31 PM
In C++ there are two kinds of methods: statically binded and dynamically binded. What they mean is that a statically binded method we know the functions address at compile time and a dynamically binded method we don't know. So like if we


class A {
public:
void print() const { cout << "A" << endl; }
};

print() is statically binded. A call like this
A a; a.print() will in psuedo assembly will look like call print(&a). The "this" pointer is passed implicitly into the method in c++. So this is simple and what c++ does on default. The problem occurs when we do something like this


class B : public A {
public:
void print() const { cout << "B" << endl; }
};

The idea was to override the behavior of A and this does work as long as the complier knows that the object is of type B. So
B b; b.print() or B* bptr = new B; b->print(); will both print out "B". The problem though is that when we write something like this A* a = new B; a->print(); the compiler does not know that a is really B a subtype of A. Therefore this will print out "A".

Dynamic binding or virtual binding solves this problem. We make a method virtual by doing this


class A {
public:
virtual void print() const { cout << "A" << endl; }
};

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

Now we can write A* a = new B(); a->print() and it will print out "B".