I would like to inherit a member function without redefining it, but giving it different default values. What should I do?
class Base{
public:
void foo(int val){value=val;};
protected:
int value;
};
class Derived : public Base{
public:
void foo(int val=10);
};
class Derived2 : public Base{
public:
void foo(int val=20);
};
void main(){
Derived a;
a.foo();//set the value field of a to 10
Derived2 b;
b.foo();//set the value field of b to 20
}
Don’t use defaults, use overloading:
class Base{
public:
virtual void foo() = 0;
protected:
void foo(int val) { value = val; }
private:
int value;
};
class Derived : public Base {
public:
void foo() override { Base::foo(10); }
};
class Derived2 : public Base {
public:
void foo() override { Base::foo(20); }
};
override
modifier is C++11.
No, you can't. But you can implement it like this.
class Base{
public:
virtual int getDefaultValue() = 0;
void foo(){value = getDefaultValue();};
protected:
int value;
};
class Derived : public Base{
public:
int getDefaultValue() {
return 10;
}
};
class Derived2 : public Base{
public:
int getDefaultValue() {
return 20;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With