Ja Jang Myeon
Ja Jang Myeon

Reputation: 41

Trying to access a function in a vector of classes w/o changing the private-status of the vector

I am trying to find a way to make the following piece of code work, WITHOUT changing the access of the betasAlphaVector from private to public. Perhaps a function that returns a pointer to the element of a selected element, that can then work? I don't know. Stymied and frustrated. Help, please?

#include <algorithm>
#include <condition_variable>
#include <vector>

using namespace std;

class Alpha {

private:
    int anInt;

public:

    Alpha(int arg) { anInt = arg; }

    Alpha(const Alpha& orig) { }

    virtual ~Alpha() { }

    void Printf() { printf("%s: anInt = %d\n", __func__, anInt); }

};

class Beta {

private:    // Can not change protection (private) status of betasAlphaVector
        std::vector<std::unique_ptr<Alpha>> betasAlphaVector;
public:
    int maxAlphas;

public:

    Beta(int arg) { maxAlphas = arg; }

    Beta(const Beta& orig) { }

    virtual ~Beta() { }

    void AddAlpha(int arg) { betasAlphaVector.emplace_back(new Alpha(arg)); }

    int SizeAlpha() { return (int) betasAlphaVector.size(); }

};

#define MaximumAlphas 3

int main(int argc, char** argv) {

    Beta *beta = new Beta(MaximumAlphas);

    for (int i = 0; i < beta->maxAlphas; i++)
        beta->AddAlpha(i*10);

    printf("%s: Alpha vector size = %d\n", __func__, beta->SizeAlpha());

    beta->betasAlphaVector.at(1)->Printf();

    return 0;
}

Upvotes: 0

Views: 49

Answers (1)

zett42
zett42

Reputation: 27766

You almost gave the answer:

Perhaps a function that returns a pointer to the element of a selected element, that can then work

Turning that into code (your other code omitted for brevity):

class Beta {
public:
    Alpha* GetAlpha( int index ) { return betasAlphaVector.at( index  ).get(); }
    const Alpha* GetAlpha( int index ) const { return betasAlphaVector.at( index ).get(); }
};

The second overload enables you to call the GetAlpha() method even when the Beta object is declared as const.

In main():

beta->GetAlpha( 1 )->Printf();

Upvotes: 1

Related Questions