my question is about inheritance and polymorphism in C++.
class Base
{
public:
virtual void f() { cout << "Base::f()" << endl; }
void f(string s) { cout << "Base::f(string)" << endl; }
};
class Derivate1: public Base
{
public:
void f() { cout << "Derivate1::f()" << endl; }
void f(int i) { cout << "Derivate1::f(int)" <<endl; }
};
class Derivate2: public Base
{
public:
void f() { cout << "Derivate2::f()" << endl; }
void f(char c) { cout << "Derivate2::f(char)" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
//with base pointers
Derivate1 d1;
Derivate2 d2;
Base *b1 = &d1;
Base *b2 = &d2;
b1->f(); //output: Derivate1::f() ok.
b1->f("string"); //output: Base::f(string) ok.
b1->f(1); //error !
b2->f(); //output: Derivate2::f() ok.
b2->f("string"); //output: Base::f(string) ok.
b2->f('c'); //error !
//with direct derivate object
d1.f(); //output: Derivate1::f() ok.
d1.f("string"); //error !
d1.f(1); //output: Derivate1::f(int) ok.
d2.f(); //output: Derivate2::f() ok.
d2.f("string"); //error !
d2.f('c'); //output: Derivate2::f(char) ok.
return 0;
}
If i want to use a redefined function in base class which is accessible in derived object, what i have to do? I don't want to use Base::f;
in derived classes.