1

I want to declare a variable size (not really variable size) array/vector inside a C++ class and I am encountering weird errors. I have tried to find a solution to this but cannot resolve the error. C++ gods, bless me.

class threeStack{
    private:
        int numberOfStacks = 3;
        int sizeOfEachStack = 2;
        int kc = 10;
        vector <int> a(numberOfStacks * sizeOfEachStack);
        vector <int> tops(numberOfStacks);
        };

ERRORS

         vector <int> a(numberOfStacks * sizeOfEachStack);
                        ^~~~~~~~~~~~~~
main.cpp:10:27: error: ‘numberOfStacks’ is not a type
         vector <int> tops(numberOfStacks);
                           ^~~~~~~~~~~~~~
Anant
  • 302
  • 2
  • 11

2 Answers2

0

You don't specify constructor arguments to class members when they are declared. That's done in the contructor of the class itself.

class threeStack{
    private:
        int numberOfStacks;
        int sizeOfEachStack;
        int kc;
        vector <int> a;
        vector <int> tops;

    public:
        threeStack() : numberOfStacks(3), sizeOfEachStack(2), 
                       kc(10), a(3 * 2), tops(3) {
        }

        threeStack(int numberOfStacks, int sizeOfEachStack) : 
            numberOfStacks(numberOfStacks),
            sizeOfEachStack(sizeOfEachStack),
            kc(10), 
            a(numberOfStacks * sizeOfEachStack), 
            tops(sizeOfEachStack) 
        {
        }
};

Also, default initialization of data members is a feature of C++11 and later, so if you're compiling with an older version of the standard you'll need to specify those in the constructor as well.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    "You don't specify constructor arguments to class members when they are declared, nor can you specify default values." Of course you can. It is called default member initializer – phön Jul 08 '21 at 12:23
0

This is declaration of a function:

vector <int> tops(numberOfStacks);
|            |   ||
|            |   |type of first parameter
|            |   parameter list
|            name of the function
return type

You cannot use this syntax for default member initialiser.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • can you recommend me something which I can read to learn this stuff? atleast the basics, I am currently reading "accelerated c++" though. – Anant Jul 08 '21 at 12:09
  • @Anant There's a list of books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). I cannot vouch for any particular book myself. My only C++ book is some old edition of Bjarne's The C++ Programming Language. – eerorika Jul 08 '21 at 12:13
  • 2
    "Also, you cannot refer to other members in a default member initialiser." I think you can? http://coliru.stacked-crooked.com/a/2824f8cf7a4ff0c6 – phön Jul 08 '21 at 12:18
  • 1
    @phön I guess I just assumed that ¯\\_(ツ)_/¯ – eerorika Jul 08 '21 at 12:20
  • @eerorika ¯\\_(ツ)_/¯ – phön Jul 08 '21 at 12:21