Reputation: 115
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.
Upvotes: 2
Views: 191
Reputation: 11157
C++ is usually very strict on this type of inheritance, if you'd like a work around you could use this to solve issues like this d1.f();
:
static_cast<Base*>(&d1)->f("string");
if you'd like to make calls like this: b1->f(1);
well.. you can't. That's the whole point of polymorphism. You'd have to declare a virtual method in the Base
class that has a method named f(int i)
so that the compiler can link the Base
class method and the Derivate1
class method:
class Base
{
public:
//...
virtual void f(int i) { printf("Base::f(int)"); }
};
Upvotes: 0
Reputation: 755357
In this case you need to tell C++ that you want to include the base class definition of f
in the derived class. This is done with a using
statement
class Derivate1: public Base
{
public:
using Base::f;
...
};
class Derivate2: public Base
{
public:
using Base::f;
...
};
This essentially tells the C++ compiler to include both the derived class and parent class definitions of f
when doing name lookup. Without this the C++ compiler will essentially stop at the first type in the hierarchy which has a member named f
and consider only the overloads declared in that type.
Upvotes: 2