Re: How about virtual function work for dervided class of dervided class of abstract class?
Thomas Maeder wrote:
"milochen" <milochen.bbs@jupiter.csie.ntu.edu.tw> writes:
class A{
virtual void forsome()=0;
};
class B:public A{
void forsome();
};
class C:public B{
void forsome();
};
void main(){
The return type of main() has to be int. This shouldn't compile.
B* B_obj = new B();
C* C_obj = new C();
f(B_obj); // I know that B::forsome() will be excuted by callee
f is undeclared here ...
f(C_obj); // C::forsome() wll be executed or B::forsome() will be
excuted?
... and here.
If all my guesses about your real code are right, C::forsome() will be
called. If you'd like to get more than guesses, please throw your code
at a compiler before posting.
}
void f(A* someobj){
A->forsome();
A is the name of a type. This certainly won't compile.
Because I posted it in that day, I have no complier with
the computer which I use, since I was serving in Navy and
therefore cannot bring my own computer.
Yes, you are right!
As long as I didn't write a real code to which compile,
I wouldn't understand it accurately.
Just learn C++ in the book is not enough.
============================
#include "iostream.h"
class A{
public:
virtual void show()=0;
};
class B:public A{
public:
void show();
};
class C:public B{
public:
void show();
};
class D:public B{};
void A::show(){
cout<<endl;
cout<<"show A"<<endl;
}
void B::show(){
cout<<endl;
cout<<"show B"<<endl;
}
void C::show(){
cout<<endl;
cout<<"show C"<<endl;
}
void f(A& someobj){
someobj.show();
cout<<"with call by reference."<<endl;
}
void g(A* someobj){
someobj->show();
cout<<"with call by address."<<endl;
}
void main(){
B objB;
C objC;
D objD;
g(new B());
g(new C());
g(new D());
f(objB );
f(objC );
f(objD );
}
I compile the above code by MS VC++98, and
the output of this problem as the following
show B
with call by address.
show C
with call by address.
show B
with call by address.
show B
with call by reference.
show C
with call by reference.
show B
with call by reference.
Press any key to continue
=============================
So Valentin Samko is right.
From this code, I could learn three point.
point 1.
the virtual function marked by'virtual' will act on
not only directly derived class but also undirectly derived class.
point 2.
the pure virtual function marked by'virtual ... =0;' will
act on directly derived class but not undirectly derived.
So we know that pure virtual function can restrict its
directly derived class to decaralation some except that
undirectly one.
point 3.
No direct decaralation 'void show()' on class D, but
virtual function still be act since by override.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]