Vector like protected attribute?
is there a possibility to create a vector in the base class and then inherit it?
Last edited on
to create a vector in the base class and then inherit it |
Like what?
Like this:
1 2 3 4 5 6 7 8
|
#include <vector>
class MyClassOne {
private:
std::vector myvec;
};
class MyClassTwo : public MyClassOne {};
|
Or like this:
1 2 3
|
#include <vector>
class MyVec : public std::vector {};
|
I mean, if i have a program like this:
1 2 3 4 5 6 7
|
class DerivedClass1: public BaseClass{
private:
vector<unique_ptr<BaseClass>> vec;
....
}
|
1 2 3 4 5 6 7
|
class DerivedClass2: public BaseClass{
private:
vector<unique_ptr<BaseClass>> vec;
....
}
|
I would prefer to insert the vector in the base class and then inherit it in derivatives
Like this
1 2 3 4 5 6 7
|
class BaseClass{
protected:
vector<unique_ptr<BaseClass>> vec;
.....
}
|
Is it possible?
Well, it seems to work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream>
#include <memory>
#include <vector>
class BaseClass {
public:
int id {};
BaseClass() = default;
BaseClass(int id_arg)
: id { id_arg }
{
}
void addElemToVec(int id_arg)
{
vec.emplace_back(std::make_unique<BaseClass>(id_arg));
}
protected:
std::vector<std::unique_ptr<BaseClass>> vec;
// friend:
friend std::ostream& operator<<(std::ostream & os, const BaseClass & rhs)
{
return (os << rhs.id);
}
};
class DerivedClass : public BaseClass {
// friend:
friend std::ostream& operator<<(std::ostream & os, const DerivedClass & rhs)
{
for(const auto & e : rhs.vec) {
os << e.get()->id << ' ';
}
return os;
}
};
int main()
{
DerivedClass dc;
dc.addElemToVec(1);
dc.addElemToVec(2);
dc.addElemToVec(3);
std::cout << dc << '\n';
}
|
Have you already taken std::reference_wrapper into consideration?
https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper
Topic archived. No new replies allowed.