Question

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.
}
Was it helpful?

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") {};

OTHER TIPS

Each instance of A/B has its own variables.

Not so. You've declared them static. Stop doing that and you might get closer to your desired result.

No, you got it wrong.

  • The problem requires each instance to have its own set of variables, so why are you declaring A and B's data as static?
  • You don't need to implement anything. The problem just asks you to declare the types and their member data.
  • The constructor isn't necessary either as far as what the requirements ask you to do.
class A{
protected:
    char var1,var2;
};

class B: public A {
private:
    char var3;
};

void main()
{
    B b1;
    b1.var3='a';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top