Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method using different flavors of it's own private members

Tags:

c++

class A{

private:

  std::vector<class X> flavor1
  std::vector<class X> flavor2

public:

  void useVectorOfX(std::vector<class X> someflavor){
      ...  // same logic for both flavors
  }    
}

Now I want to call useVectorOfX() from another class, giving it either flavor1 or flavor2 depending on need. I can think of three ways -

Way 1: Use Getter Methods; but it seems unnatural for class A to get its own data through a Getter Method.

class B{

public:

  A *a = new A();
  a->useVectorOfX(a->getFlavor1());
}

Way 2: Make the two vectors public (dirty)

Way 3: Separate Methods?

class B{

public:

  A *a = new A();
  a->useVectorOfXForFlavor1();
  a->useVectorOfXForFlavor2();

}
like image 545
Vaibhav Bajpai Avatar asked Dec 27 '22 18:12

Vaibhav Bajpai


1 Answers

What about way 1 in a more descriptive format:

class A {    
public:
    enum {
        flavor1 = 0, // used as array index, first element must be zero
        flavor2,
    } vector_flavor;
    static const int number_of_flavors = 2;

    void useVectorOfX(vector_flavor flav){
        std::vector<class X> someflavor& = vectors[flav];
        // ...
    }
private:        
    std::vector<class X> vectors[number_of_flavors];
}

A object; // lol
object.useVectorOfX(A::flavor1);
like image 184
orlp Avatar answered Feb 01 '23 23:02

orlp