S.Tarafdar
08-24-03, 03:52 AM
I have this code:
#include<iostream>
#include<string>
using namespace std;
class A{
protected:
int counter;
void printhelper(string name) const{
cout<<name<<":"<<counter<<endl;
}
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<3;i++){
list[i]->action();
}
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
#include<iostream>
#include<string>
using namespace std;
class A{
protected:
int counter;
void printhelper(string name) const{
cout<<name<<":"<<counter<<endl;
}
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<3;i++){
list[i]->action();
}
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