Initializing an abstract class?

Here is my problem. I want to have something like this:

class A {
protected:
int someInt;
virtual void someFunc() = 0;

};

class B : public A {
protected:
virtual void someFunc() { // uses someInt}
public:
B() {//tell the A inside of B to set someInt to whatever it wants}
};

so basically, someInt can be changed, it is not constant, but I want all classes that implement A to use the value provided by A for someInt.

thank

+3
source share
4 answers

You can use the initializer lists in the constructor to call the parent constructors:

class A {
protected:
    int someInt;
    virtual void someFunc() = 0;
    A(int x) : someInt(x) {}  // Base-class constructor (initialises someInt)
};

class B : public A {
protected:
    virtual void someFunc() {}
public:
    B() : A(10) {}  // Initialises base class via constructor
};
+4
source

Is this what you want?

class A
{
protected:
    int someInt;

public:
    A(int _val) : someInt(_val)
    {
    }; // eo ctor
}; // eo class A


class B : public A
{
public:
    B() : A(5) // initialise someInt with 5
    {
    }; // eo ctor
}; // eo class B

Note that since "someInt" is protected, you can simply set it in constructor B anyway.

    B()
    {
        A::someInt = 5;
    }; // eo ctor
+1
source

, , someInt A, .

class A {
public:
    A() : someInt(5) {}
protected:
int someInt;
virtual void someFunc() = 0;

};

class B : public A {
protected:
virtual void someFunc() { // uses someInt}
public:
B() {// at this point someInt will already have been initialized to 5}
};

.

0
class A {
protected:
    int someInt;
    virtual void someFunc() = 0;
    A(){//set someInt here}
};

class B : public A {
protected:
    virtual void someFunc() { // uses someInt}
public:
    B():A() {}
};

The protected constructor will achieve this. As stated above. Solutions using a public constructor are fine too, but since the constructor cannot be called directly on the thr interface, I think security is better.

0
source

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


All Articles