static variables in abstract base classes

P

pasa_1

Are there any reasons one should avoid using static variables in
abstract base classes?

I was considering to the following:

#include <iostream>

using namespace std;

enum { SZ = 10 };

class AbstractBaseClass
{
protected:
static int a[SZ];
public:
AbstractBaseClass() { }
virtual void foo() const = 0;
static void bar(int i) { ++a; }
};

int AbstractBaseClass::a[SZ];

class Derived: public AbstractBaseClass
{
public:
Derived(): AbstractBaseClass() { }
void foo() const
{
int i = 0;
cout << "Derived::foo(): a[" << i << "]: " << a << endl;
}
};
 
M

mlimber

pasa_1 said:
Are there any reasons one should avoid using static variables in
abstract base classes?

I was considering to the following:

#include <iostream>

using namespace std;

enum { SZ = 10 };

class AbstractBaseClass
{
protected:
static int a[SZ];
public:
AbstractBaseClass() { }
virtual void foo() const = 0;
static void bar(int i) { ++a; }
};

int AbstractBaseClass::a[SZ];

class Derived: public AbstractBaseClass
{
public:
Derived(): AbstractBaseClass() { }
void foo() const
{
int i = 0;
cout << "Derived::foo(): a[" << i << "]: " << a << endl;
}
};


There's no inherent problem with them, but you should initialize them
when you define them. Also consider using a container rather than a raw
array (http://www.parashift.com/c++-faq-lite/containers.html#faq-34.1).

Cheers! --M
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top