开发者

C++ reference in base class constructor

开发者 https://www.devze.com 2023-01-19 00:48 出处:网络
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?

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.

0

精彩评论

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