开发者

Initializing an abstract class?

开发者 https://www.devze.com 2023-01-23 15:17 出处:网络
Here is my issue. I want to have something like this: class A { protected: int someInt; virtual void someFunc() = 0;

Here is my issue. 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开发者_StackOverflow to set someInt to whatever it wants}
};

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

Thanks


You can use initializer lists in the constructor to call 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
};


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 as "someInt" is protected, you can just set it in B's constructor anyway.

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


I am not sure what you want, but if you initialize someInt in the constructor of A, subclasses will see that value.

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}
};

When the subclass is constructed, the baseclass constructors are executed first.


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() {}
};

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

0

精彩评论

暂无评论...
验证码 换一张
取 消