开发者

c++ polymorphism and other function question

i have got this code:

class father{
public:
    virtual void f() { cout<<1;}
};

class son:public father{
public:
    void f() {cout<<2;}
};

void test (father x){x.f();}

int main(){
    开发者_如何学Cson s;
    test(s);
}

the question says:

  1. the output is '1', what is the rule about polymorphism that the programmer forgot and how can i fix it so the output would be '2'?

  2. there is another rule that the programmer forgot when he wrote the father class, and he need to add an empty function to avoid problems from other sons of the father class. what is the rule and what is the missing function?


another question write the g function so the next code would run with no crashes

int x=11; g(x)=22;


When you pass the son object to the test function by value, it will be converted to a father object because test takes a father, not a son. If you want to accept instances of subclass without conversion, you need to accept the argument by reference or pointer.

So if you change the signature of test to void test (father& x), it will work as you want.


I tell my C++ students (in second year) that polymorphism will never sneak up on them; first you need an inheritance hierarchy, and second you need to be using pointers.


  1. Pass son s to test as a reference, rather than a copy. If s is passed as a copy, it will be cast to a father object in test. By using a reference of s instead, it will still behave, properly, as a son object.

  2. I think this is referring to the recommendation that any base class should have a virtual destructor. That way, the object can be properly destroyed through a pointer or reference of its base class.

add to father:

virtual ~father() {}


You passed x by value. So the compiler will reduce the son object to a father object, including its virtual function table. If you want to call a virtual function of father in test, you need to pass x either by reference or by pointer.


What is it about the test function that makes you think the output would be 2?


In the function "test" the parameter "father x" is not a reference to class, it IS an instance of father that will be copy constructed from the passed parameter.


Well u could also make some changes in ur main regarding this problem like making pointer to your base class I.e father and point it to address of ur child class obj then further use that as per ur requirement.

This is what the basic structure of polymorphism.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜