Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 551
shanks3042 Avatar asked Dec 17 '25 20:12

shanks3042


1 Answers

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_.

like image 71
stv Avatar answered Dec 19 '25 09:12

stv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!