Constants in base classes

O

Omer

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?
Thanks a lot in advance,
Omer.
 
L

Leandro Melo

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top