Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class initialization with vector

I have inherited some code that I am looking at extending, but I have come across a class\constructor that I have not seen before. Shown below in the code snippet

class A {
 public:
    A() {};
    ~A() {};
 //protected:
    int value_;

class B: public std::vector<A> {
  public:
    B(int size = 0) :
      std::vector<A>(size)
    {}

So from what I gather class B is a vector of class A which can be accessed using the *this syntax because there is no variable name. I would like to initiate class A in the constructor, but I am unsure how to do this with in this context. I have looked at this but they have declared the vector as an object where in this case it is the class.

This seems slightly different from normal inheritance where I have inherited many instances of a single class, compared to the usual one to one in most text books. What I was trying to do, was propagate a value to intialise class A through both class B and class A constructor. Something like below is what I tried but doesn't compile.

#include <iostream>
#include <vector>
using namespace std;
class A {
 public:
    A(int int_value) :
    value_(int_value)
    {};
    ~A() {};
 //protected:
    int value_;
};

class B: public vector<A> {
  public:
    B(int size = 0, int a_value) :
      vector<A>(size, A(a_value))
    {};

    vector<int> new_value_;

    void do_something() {
        for (auto& element : *this)
            new_value_.push_back(element.value_);
    }
};

int main() {
    cout << fixed;
    cout << "!!!Begin!!!" << endl;
    B b(20,23);
    cout << b.size() << endl;

    b.do_something();
    for(auto& element : b.new_value_)
        cout << element << endl;

    cout << "finished" << endl;
    system("PAUSE");
    return 0;
}

I guess a follow up question is, is this a good implementation of what this code is trying to achieve

like image 481
Cyrillm_44 Avatar asked Feb 03 '26 00:02

Cyrillm_44


1 Answers

B(int size = 0, int a_value) ... 

is incorrect. You may not have an argument with a default value followed by an argument that does not have a default value.

Possible resolutions:

  1. Provide default values for both arguments.

    B(int size = 0, int a_value = 0) ... 
    
  2. Provide default value only for the second argument.

    B(int size, int a_value = 0) ... 
    
  3. Change so that neither has a default value.

    B(int size, int a_value) ... 
    
like image 138
R Sahu Avatar answered Feb 04 '26 15:02

R Sahu