#include <iostream>
using namespace std;
class x{
public:
virtual void print(double a,int x) {cout<<"Class x"<<endl;}
};
class y: public x{
public:
void print(char a) {cout<<"Class y char: "<<a<<endl;}
};
int main()
{
y *t = new y();
t->print(1.0,2); //Does not work, if function name matched in derived class, it will not look in parent, even if the matched function can't be executed.
return 0;
}
This code, only looks in the derived class for function "print" and does not go to the parent class for lookup ever, as expected.
But,
#include <iostream>
using namespace std;
class x{
public:
virtual void print(double a) {cout<<"Class x double"<<endl;}
virtual void print(int a) {cout<<"Class x int"<<endl;}
};
class y: public x{
public:
void print(double a) {cout<<"Class y double"<<endl;}
void print(char a) {cout<<"Class y char"<<endl;}
};
int main()
{
x *t = new y();
t->print(1);//this calls print(int) in base/parent class x
return 0;
}
This code looks into the derived class after it does not find exact matching signature and name in derived class, it goes into base class.
I know that the lookup process for a non polymorphic object of derived class is:
Looks into base class for matching function name
if found ->
if exectuable -> execute, else -> errorelse -> error
But I want to know the lookup process for the polymorphic objects.
EDIT:
If the second case only looks into the base class then,
3)
#include <iostream>
using namespace std;
class x{
public:
virtual void print(double a){cout<<"Class x double"<<endl;}
virtual void print(int a) {cout<<"Class x int"<<endl;}
};
class y: public x{
public:
void print(char a) {cout<<"Class y char: "<<a<<endl;}
void print(double a) {cout<<"Class y double"<<endl;}
};
int main()
{
x *t = new y();
t->print('a');//works
return 0;
}
#include <iostream>
using namespace std;
class x{
public:
virtual void print(double a){cout<<"Class x double"<<endl;}
//virtual void print(int a) {cout<<"Class x int"<<endl;}
};
class y: public x{
public:
//void print(char a) {cout<<"Class y char: "<<a<<endl;}
void print(double a) {cout<<"Class y double"<<endl;}
};
int main()
{
x *t = new y();
t->print(1.0);//calls y::print(double)
return 0;
}
Why does case 3 work, where derived class y::print(char) is called and case 4 where y::print(double) is called (which is the entire point of polymorphism with virtual functions)?