C ++ Initialization Constants and Inheritance

I want to initialize a constant in the child class instead of the base class. And use it to get rid of dynamic memory allocation (I already know the size of the array, and there will be several child classes with different constants).
Therefore, I try:

class A {
public:
    const int x;

    A() : x(0) {}
    A(int x) : x(x) {}
    void f() {
        double y[this->x];
    }
};

class B : A {
    B() : A(2) {}
};

Pretty simple, but the compiler says:

error C2057: expected constant expression

How can I tell the compiler that it really is a constant?

+3
source share
4 answers

. . . " ", , , , ​​ "52" "45" - .

std::vector .

EDIT: " , "

- .

template<size_t x>
class A {
public:
    void f() {
        double y[x];
    }
};

typedef A<2> B;
+4

.

, , "". std::vector.

template <size_t a = 0>
class A {
public:
   A() { }

   void f() {
      int y[a];
      y[0] = 5;
   }
};

class B : A<2> {
   B() { }
};

void main() {
   A<1> a;
   a.f();

   // Undefined behaviour - creating an array of size 0
   // At least, MSVS2008 treats it as an error :)
   // A<0> a_;
}
+2

"", "". , , , , . , gcc ( ++), .

+1

, , - :

template <int size>
class A { 
    double y[size];
};

, , A B .

Another obvious possibility would be to use an object tr1::array. It is also a template, so the idea is almost the same, but it has already been written, tested and works, so you can avoid all this. If your compiler does not provide TR1 classes, Boost has basically the appropriate implementation ( boost::array).

+1
source

Source: https://habr.com/ru/post/1750399/


All Articles