Baruch Burstein said:
Actually, I am trying to privatize a public variable. The base class
has no need to know when the variable changes, and therefore I made it
public directly; why use get/set methods that do nothing (right?). The
derived class needs to adjust some of it's own settings according to
that one, so it needs to know when it is changed (get/set methods). Am
I totally misusing inheritance?
I have to say I am not quite understanding your motivations for doing it
this way. Having a base class data member be public just for the sake
of not having to provide get/set methods seems odd, particularly where
there are other ways of achieving what (I believe) your are trying to
do.
In order to take up on Leigh's solution, let's suppose you are wanting
to do something like the following (and you'll correct me if I am wrong
in my assumption):
class Base {
public:
Base(int i) : i_(i) { }
int i_;
void foo() { }
void bar() { }
};
class Derived : private Base {
public:
Derived(int i = 0) : Base(i) { }
using Base::foo;
using Base::bar;
void baz() { }
};
int main()
{
Derived d;
d.foo();
d.bar();
d.baz();
// int j = d.i_; // error: inaccessible
}
But then what would be wrong, given that you are wanting to avoid
accessors in your base class, with something like:
class Base {
protected:
int i_;
public:
Base(int i) : i_(i) { }
void foo() { }
void bar() { }
};
class Derived : public Base {
public:
Derived(int i = 0) : Base(i) { }
void baz() { }
};
int main()
{
// same as before
}
As to your ultimate question, "Am I totally misusing inheritance," I
would suggest probably yes. Your argument against avoiding what I might
call good design is trivial and merely introduces complications for no
real advantage as I can see it. Personally, I would go for something
like:
class Base {
private:
int i_;
protected:
void seti(int i) { i_ = i; }
int geti() const { return i_; }
public:
Base(int i) : i_(i) { }
void foo() { }
void bar() { }
};
class Derived : public Base {
Derived(int i = 0) : Base(i) { }
void baz() { seti(geti() * 2); }
};
int main()
{
Derived d;
d.foo();
d.bar();
d.baz();
// int j = d.i_; // error: inaccessible
// j = d.geti(); // error: inaccessible
}
All this is still dependent upon your actual use case and follows your
requirement that Base does not require the getter/setters for its
own purposes (adding that they should not be public either). They are
trivial enough to benefit from inlining in any case.
Regards
Paul Bibbings