Chris
Chris

Reputation: 65

Initialization of base class value for derived class

I want to create ab object of the base class Foo that initializes the variable value to something I decide, I then want to create an object of the derived class Bar and the variable value I decided earlier sticks with Foo that Bar inherits, like a constant one time initialization for the variable value.

Is there a way to do this without passing in the value every time I create the Bar object like with the Foo object or make the class value default to 5?

Example:

// Base class
class Foo {
private:
    int value;
public:
    Foo() {}
    Foo(int value) : value(value) {}
    int getValue() { return value; }
};

// Derived class
class Bar : public Foo {
private:
public:
    Bar() {}
};

Foo foo(5);
foo.getValue() // 5
Bar bar;
bar.getValue() // this I also want to be 5 now 

Upvotes: 0

Views: 110

Answers (1)

Curious
Curious

Reputation: 21540

You can do this with static variables, either in class scope or method scope (with the latter having some differences, like lazy initialization, thread safe initialization, etc. Although, it does not make a big difference in your use case, but it is good to keep the latter in mind as an option). For example

#include <iostream>

using std::cout;
using std::endl;

// Base class
class Foo {
private:
    static int value;
public:
    Foo() {}
    Foo(int value) {
        Foo::value = value;
    }
    int getValue() { return value; }
};

int Foo::value = 0;

// Derived class
class Bar : public Foo {
private:
public:
    Bar() {}
};

int main() {
    Foo foo(5);
    cout << foo.getValue() << endl;
    Bar bar;
    cout << bar.getValue() << endl;
}

I have just provided you with a solution you want. Keep in mind that this might not be the best way to achieve what you want. An object's construction parameters should ideally only affect the current object.

Upvotes: 2

Related Questions