Assaf Karavani
Assaf Karavani

Reputation: 81

Pre-constructor initialization

My problem is like this, I have a class named "Product" and another class named "Agriculture", the "Agriculture" class is inheriting the "Product" class.

When I summon the "Agriculture" constructor obviously the "Product" constructor is summoned first.

The question is, can I initialize one of the product's members via a set method first?

Upvotes: 1

Views: 2227

Answers (2)

JackChen255
JackChen255

Reputation: 395

Product constructor is called firstly, and you set some values inside this constructor. So why you still want to initialize one of the product's members via a set method first?

Upvotes: 1

Christophe
Christophe

Reputation: 73376

If you have:

class Product { ... };
class Agriculture : public Product { ...}; 

you can't escape the standard rule that the base object is constructed before the derived object. You have no chance to intervene in this order, nor set anything in Product before it's constructor starts.

Recommendation:

The best design for your need would be to foresee a Product constructor that takes as additional parameter(s) the value(s) that you want to set:

 class Product {
     string origin; 
 public:  
     Product () : origin("tbd") { } 
     Product (string withorigin) { ...}
     void setOrigin (string myorigin) { origin=myorigin; }  
 };
 class Agriculture : public Product {
 public: 
     Agriculture () : Product ("Earth") { ...} 
 };

Workaround:

If such design would not fit your needs, the only thing you could imagine, would be to have a static member in Product. This member would then be independent of any Product, and could thus be set before an object is constructed.

 class Product {
     static string defaultCurrency; 
     string currency;
 public:  
     Product () : currency(defaultCurrency) { ... } 
     static void setDefaultCurrency (string cur) { defaultCurrency=cur; }  
 };
 class Agriculture : public Product { ...  };

 int main() {
     Product::setDefaultCurrency("EUR"); 
     Agriculture a1; 
 }

It's more error prone: the construction result depends on order of operations not related to the construction. This could be a problem for example in case of multithreading, if several threads construct objects at same moment.

Upvotes: 3

Related Questions