static variables in abstract base classes

Discussion in 'C++' started by pasa_1, Nov 17, 2006.

  1. pasa_1

    pasa_1 Guest

    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;
    }
    };
    pasa_1, Nov 17, 2006
    #1
    1. Advertising

  2. pasa_1

    mlimber Guest

    pasa_1 wrote:
    > 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
    mlimber, Nov 17, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. DaKoadMunky
    Replies:
    4
    Views:
    547
    Lee Weiner
    Apr 20, 2004
  2. John Gagon
    Replies:
    1
    Views:
    367
    LordAlfredHenry
    May 17, 2006
  3. Ben Finney

    Abstract Base Classes

    Ben Finney, Nov 11, 2005, in forum: Python
    Replies:
    6
    Views:
    404
    Steven D'Aprano
    Nov 14, 2005
  4. pasa_1
    Replies:
    0
    Views:
    299
    pasa_1
    Nov 17, 2006
  5. Bart Simpson
    Replies:
    4
    Views:
    308
    James Kanze
    Jun 3, 2007
Loading...

Share This Page