Search code examples
c++variablesscopedeclare

C++ Variables - declare and define. Inheritance


Let's have a C++ object A. There are two variables (VAR1 and VAR2) in A accessible to its children. Object B extends A and has one private variable VAR3 it can also access VAR1 and VAR2. Each instance of A/B has its own variables.

Would this be the right way of declaring and defining the variables?

A.h


class A {
protected:
    static std::string const VAR1;
    static std::string VAR2;
};

A.cpp


#include "A.h"
using namespace std;
string const A::VAR1 = "blah";
string A::VAR2;

B.h


#include "A.h"
class B : public A {
private:
    static std::string VAR3;

public:
    B(std::string const v1, std::string const v2);
    void m() const;
};

B.cpp


#include "B.h"
using namespace std;

string B::VAR3;

B::B(string const v1, string const v2) {
    VAR2 = v1;
    VAR3 = v2;
}

void B::m() const {
    // Print VAR1, VAR2 and VAR3.
}

Solution

  • Each instance of A/B has its own variables.

    Would this be the right way of declaring and defining the variables?

    No. You've declared A's members as static which means they are class-variables, not instance-variables. Each instance doesn't get it's own copy. Instead, they all share the same instance.

    Make then non-static:

    class A {
    protected:
        std::string const VAR1;
        std::string VAR2;
    };
    

    ... and then, of course, you don't need the global initializer so get rid of this:

    string const A::VAR1 = "blah";
    string A::VAR2;
    

    ...and if you want VAR1 to have a default value every time A is instantiated, then you can do that in the class' initializer list (or in the ctor body, if you're a punk :) ):

    A::A() : VAR1("blah") {};