Polymorphism in C++: Do I have to give child class functions the same arguments as the parents - how to overload
If I have a parent class like this:
class Parent {
protected:
virtual void foo(type1 var1, type2 var2);
}
and a child class:
class Child : 开发者_JAVA技巧public Parent {
foo(type1 var1, type2 var2);
}
but what if the foo
function in Child
doesn't need var1
and var2
? Is there a way to tell the compiler not either not give memory to these variables because they're not being used? Or, how do you overload it? Combining overloading and polymorphism though.. how do you do that (if you can/would!).
Thank you.
If the child's function signature is different to the partent's, then the child has two functions which are overloaded.
The compiler will pick the right one according to which kind of arguments you give it. One can modify its arguments and forward the work to another function if it likes.
For example,
class Child : public Parent {
using Parent :: foo;
void foo (type1 var1);
};
Child c;
child .foo (type1()); // Valid
child .foo (type1(), type2()); // Valid, calls Parent::foo
void Child :: foo (type1 x) {
Parent :: foo (x+1, blah);
}
Or, if you want to disambiguate.
class Child : public Parent {
void foo (type1 var1, type2 var2);
};
Child c;
child .foo (type1(), type2()); // Valid, calls Child::foo
child .Parent :: foo (type1(), type2()); // Valid.
Overriding is something else.
class Parent {
virtual void foo () {}
};
class Child1 : parent {
void foo ();
};
class Child2 : parent {
void foo ();
};
void call_foo (Parent & p) {p .foo ();}
Parent p;
Child1 c1;
Child2 c2;
call_foo (p); // Calls Parent::foo
foo (c1); // Calls Child1::foo
foo (c2); // Calls Child1::foo
You simply have to define another foo function in Child class with different signature (i.e. different argument). This is overloading function foo. The compiler will execute the correct function according to the parameters you put.
精彩评论