shanks3042
shanks3042

Reputation: 33

How to initalize a vector inherited from base class in derived constructor

I know that i can iniatlize the vector of the base class in the derived like this:

Base.h

#include <vector>
#include <utility>

public:
  Base(std::vector<std::pair<int, int> > vec);
  ~Base();
private:
  std::vector<std::pair<int, int> > vec_;

Base.cpp

Base::Base(std::vector<std::pair<int, int> > vec) : vec_(vec)
{
}

Derived.cpp

Dervied::Derived : Base({{0, 0}, {1, 1}})
{
}

But is there also a way to initalize the vector vec_ of this base class in the child?

Base.h

#include <vector>
#include <utility>

public:
  Base();
  ~Base();
private:
  std::vector<std::pair<int, int> > vec_;

Base.cpp

Base::Base()
{
}

So something like:

Derived::Derived : Base(vec_({{0, 0}, {1, 1}}))

Or is this not possible at all in C++?

Upvotes: 3

Views: 297

Answers (1)

stv
stv

Reputation: 36

vec_ is private. Hence, it is not accessible in the derived class. You could make it protected if you need to access it in the derived class.

As your classes stand at the moment, you can only modify vec_ through the base class constructor.

If there were some other base class methods accessible to the derived class that modified vec_ then you could use them to change vec_.

Upvotes: 2

Related Questions