Reputation: 7623
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(){
son s;
test(s);
}
the question says:
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'?
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;
Upvotes: 0
Views: 886
Reputation: 1
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.
Upvotes: -1
Reputation: 630
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.
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() {}
Upvotes: 2
Reputation: 370102
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.
Upvotes: 3
Reputation: 18944
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.
Upvotes: 2
Reputation: 36016
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.
Upvotes: 0
Reputation: 19940
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.
Upvotes: 1
Reputation: 49812
What is it about the test function that makes you think the output would be 2?
Upvotes: 0