Re: How to prevent a function in base class being overloaded from child class
From: Jeff Schwab (jeffrey.schwab_at_rcn.com)
Date: 03/21/05
- Next message: Victor Bazarov: "Re: Script Engine in C++"
- Previous message: Walter: "Re: Script Engine in C++"
- In reply to: modemer: "Re: How to prevent a function in base class being overloaded from child class"
- Next in thread: modemer: "Re: How to prevent a function in base class being overloaded from child class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 21 Mar 2005 17:06:37 -0500
modemer wrote:
> Suppose I am a base class designer,
> I believe my func() in base class is the best solution for certain goal.
You are entitled to your opinion.
> This base class is going to be used by other programmers, they are just
> allowed to create their own child class inherated from my base class, but I
> don't want to write any email notice to say "func() is reserved for base
> class, don't use it in your derived class,
Can you make func() private?
> otherwise base::func() will never
> be called when child::func() is called", I want to know how to let compiler
> raise an error when the programmer happened defines func() in his child
> class.
Why do you care about an unrelated function in a derived class?
If you want to limit access to the internals of your Base objects, make
those internals private, and provide access only through methods in the
base class. E.g:
#include <iostream>
struct Base {
public:
Base( ): m_i( 0 ) { }
virtual ~Base( ) { }
virtual void set( int i ) {
// Override me all you want. You can't set m_i
// without going through proper channels.
std::cout << "I am the One True Way to set m_i.\n";
m_i = i;
}
virtual int get( ) {
std::cout << "I am the One True Way to get m_i.\n";
return m_i;
}
private:
Base( Base const& ) {
throw "Don't copy Base.\n";
}
Base operator = ( Base const& ) {
throw "Don't assign to Base.\n";
}
int m_i;
};
struct Derived: Base {
void set( int i ) {
// For a compile time error, try this: m_i = i;
Base::set( i ); // Pretty much your only option.
}
};
int main( ) {
Derived d;
d.set( 3 );
}
- Next message: Victor Bazarov: "Re: Script Engine in C++"
- Previous message: Walter: "Re: Script Engine in C++"
- In reply to: modemer: "Re: How to prevent a function in base class being overloaded from child class"
- Next in thread: modemer: "Re: How to prevent a function in base class being overloaded from child class"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|