0

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 
2
  • If I understand your goal correctly, it seems doomed. You do not inherit from an object/instance of base class, you inherit from the base class, the class does not know about the value of a member variable of an existing object. Would storing a reference to the object you try to "inherit" help to achieve what you want? Commented Jul 22, 2017 at 18:09
  • Your requirement is implementing a side-effect in the base class construction that affects all following derived class constructions. This is confusing to say the least. Doing this in an object-oriented style is possible. You could write a factory class with a constructor accepting the variable value. Objects created by the factory will be created with this value. Commented Jul 22, 2017 at 18:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.