Leandro Melo
11/18/2008 11:03:00 AM
On 18 nov, 07:26, Omer <omer...@yahoo.com> wrote:
> Hi All,
> I have two classes that have the same functionality, but with
> different constants, e.g. database table name.
> I've defined a base class that gets the constants in the constructor,
> and maintain the functionality. It works fine, but not very
> efficiently.
> Here's an example:
> class base {
> public:
> base (string &const1, string @const2) {s1 = const1; s2 = const2;}
> private:
> string s1, s2;};
>
> class kid1 : public base {
> public:
> kid1 () {base ("Child 1", "Table 1");}};
>
> class kid2 : public base {
> public:
> kid2 () {base ("Child 2", "Table 2");}
>
> };
>
> My problem is that each object has all the constants as variables.
> Is there any way to improve the efficiency?
What exactly do you mean? Those strings belong to the base class part
of derived classes objects. Can you define them to be protected
instead of private? By the way, you should use the initialization list
in the constructor:
class kid2 : public base {
public:
kid2() : base("Child 2", "Table 2") {}
};
In this case it's probably a good idea for the base class constructor
to declare parameters by const-ref. (Again, use the initialization
list.)
class base {
public:
base (string const& const1, string const& const2) : s1(const1), s2
(const2) {}
protected:
string s1, s2;
};
Notice that you don't need the semi-colon (;) at the closing braces of
constructors bodies, function bodies or namespaces.
--
Leandro T. C. Melo