akolechko
akolechko

Reputation: 95

Derived Get/Set Methods

Imagine I have this code:

class A {
 public:
  void GetInt() { cout << number << endl; }
  void SetInt(int n) { number = n; }

 private:
  int number = 0;
};

class B : public A {
 public:
  void GetInt() { cout << number << endl; }

 private:
  int number = 0;
};

int main() {
  B b;
  b.SetInt(5);
  b.GetInt(); // Prints 0, needs to be 5

  return 0;
}

Is there any way to make SetInt() changing B.number without implementing it in B? Imagine I have 500 derived classes from A, and they set their number in the same { number = n; }. Do I have to implement the same SetInt() method 500 times?

Upvotes: 0

Views: 69

Answers (3)

Secundi
Secundi

Reputation: 1190

In case you really want each derived class to yield and handle its own value in terms of class hierachy separation - which I'd find at least questionable at all in terms of design and problem solution approach - you cannot avoid a minimum amount of code duplication for each derivation. At least you need the member access itself to be duplicated. There are some template/macro tricks to circumvent code explosions here (generic member instrusion), but since I really don't think, that this is what you want to achieve, I do not go into details for now.

Otherwise, idclev 463035818's answer is the way to go.

Upvotes: 0

bitmask
bitmask

Reputation: 34628

No, 0 is the correct result. In your class B you create a whole new member B::number which is independent from A:::number. So when you run A::SetInt, that member function changes A::number and when you run B::GetInt, that function accesses A::number which was never set to 5.

Try not to have members in derived types that have the same name as a member in the base class. All it does is create confusion.

Upvotes: 2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122228

The simple way to get what you ask for is this:

class A {
 public:
  void GetInt() { cout << number << endl; }
  void SetInt(int n) { number = n; }

 private:
  int number = 0;
};

class B : public A {
    // don't hide methods inherited from A
    // don't add members that are already present (as private member of A)
};

int main() {
  B b;
  b.SetInt(5);
  b.GetInt(); // Prints 5

  return 0;
}

Private members are inherited, they just cannot be accessed directly. Though as A does provide public accessors, B has acess to A::number via the setter from A.

PS A method called Get___ should actually return something, not just print the value on the screen.

Upvotes: 3

Related Questions