C++ reference in base class constructor
I have a logic in base class constructor. The result of the logic has to be captured in the derived class constructor in a temporary variable. Is there a way to do it?
F开发者_JAVA百科or example
class Base
{
Base() { int temp_value = some_logic; }
};
class Derived : public Base
{
Derived() { // need the temp value here.. }
};
Thanks, Gokul.
I guess the easiest way I can think of would be to just separate some_logic into it's own method...
class Base
{
Base() { int temp_value = initializationLogic(); }
int initializationLogic(){ return some-logic;}
};
class Derived : public Base
{
Derived() { int temp_value_here_too = initializationLogic(); }
};
Either:
class Base
{
protected int not_so_temp_value;
Base() { not_so_temp_value = some_logic_result; }
};
class Derived : public Base
{
Derived() { // read the not_so_temp_value member here.. }
};
Or:
class Base
{
Base(int some_logic_result) { int temp_value = some_logic; }
};
class Derived : public Base
{
static Derived* create()
{
int some_logic_result = some_logic;
return new Derived(some_logic_result);
}
Derived(int some_logic_result) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
This is the one i am planning to use
class Base
{
Base(int& some_logic_result) { some_logic_result = some_logic; }
};
class Derived : public Base
{
Derived(int some_logic_result = 0) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
Thanks, Gokul.
精彩评论