denz
denz

Reputation: 25

Is it good practise to encapsulate a vector using stl iterator? If it is? How could it be done?

I am fairly new to C++ and would like to implement encapsulation for my vector.

#pragma once

#include <vector>

using namespace std;

class Cell {
public:
    Cell();
    Cell(const Cell& cell);
    void setVector(vector<int> vector[]);
    vector<int> getVector(void)const;

private:
    vector<int> m_vector;
};

I recently read about STL iterators, so I would like to know if it is good practice to implement my setVector() method this way? If it is, could you give me examples on how it could be done?

Upvotes: 0

Views: 971

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27538

Instead of exposing the whole vector, be it via a reference or with iterators, you should expose only those member functions of std::vector which you actually need.

Or even more precisely: you should expose only that functionality of std::vector which you actually need.

Look at all the members provided by std::vector: Do you really need Cell to expose, say, allocator_type, back, pop_back, operator>= or shrink_to_fit?


A more robust solution which achieves actual encapsulation and not just superficial pseudo-encapsulation is to explicitly delegate to required vector member functions from Cell member functions. For example, if you only need size and individual element access, then why not just add a size member function and an elementAt member function to Cell and have the implementations of those functions delegate to the private vector?

Example:

#include <vector>

class Cell {
public:
    Cell(std::vector<int> const& vector) : m_vector(vector) {}

    int size() const
    {
        return static_cast<int>(m_vector.size());
    }

    int elementAt(int index) const
    {
        return m_vector[index];
    }

private:
    std::vector<int> m_vector;
};

Perhaps you do not even need a std::vector parameter in the constructor. You can take any input you want and initialise the private vector with it.


As an aside, best practices which will very likely be established by C++17 would also require or at least encourage you to add non-member functions size and empty to the class, in order to achieve compatibility with the std::empty and std::size functions:

bool empty(Cell const& cell)
{
    return cell.size() == 0;
}

int size(Cell const& cell)
{
    return cell.size();
}

Upvotes: 1

Related Questions