0
Code problem: polymorphism
can anyone please explain why the code is getting error? #include <iostream> using namespace std; class calc { public: virtual void result() { cout << "Base class"<<endl;} }; class sum: public calc{ public: void result(int a,int b) { cout << a+b <<endl; } }; int main() { calc c;sum s; calc *c1 = &c; calc *c2 = &s; c1->result(); c2->result(52,31); }
1 Answer
+ 2
With the keyword "virtual" you are telling the compiler the derived class might have its on implementation of a function, so you then can call it through a pointer of the base class.
However, this only works if you implement the same function in the derived class.
Remember the chapter "Functions Overloading"!
Same name != same function, if the parameters differ.
In your case void result() in the base class is unequal to void result (int, int) in the derived class.
The compiler looks for the same function in the derived class, notices there is none, so he calls the function from the base class, but that doesnt take any arguments, thats why it errors.