0

I am using bool flag to call base class function when needed to imitate virtual constructor. I am using this way for inheritance purpose. I have a Base class constructor with int and bool. The bool part is there to check whether to call fun() or not. By default I make base class flag true.

Then for Derived class I make it false so that the base class's fun() does not get called but derived class's func get called.

#include <iostream>

class A{
public:
  A(int valx, bool flag=true):x(valx){
    // initialize x with proper setting value. Called by both Base and Derived.
    init();
    if(flag){
      fun();
    }
  }
  // base way of setting value_set_based_on_obj_type.
  void fun(){
   std::cout << "base fun\n";
   value_set_based_on_obj_type = x + 2;
  }
protected:
  void init(){
   std::cout << "init" << std::endl;
   x = x*2;
  }
int x;
int value_set_based_on_obj_type;
};

class B : public A{
public:
  B(int val):A(val, false){
   fun();
  }
  // derive way of setting value_set_based_on_obj_type.
  void fun(){
   std::cout << "derived fun\n";
   value_set_based_on_obj_type = x/3;
  }
};

int main(){
  B a(1);
}

Output :

init

derived fun

Is this approach a proper way to imitate virtual constructor (Because virtual constructor is not possible in C++). Are there other ways which is more elegant then this.

Also I read some where that you should eliminate boolean arguments where possible.

  • 2
    Looks ugly to me, but there may be situations where this could be reasonable . I think this is one of those questions which cannot be seriously answered without real class names, function names, and variable names, and without seeing the real functionality controlled by "flag". – Doc Brown Feb 13 at 7:05
  • This doesn't even look like a virtual constructor to me. You explicitly create a B here. Normally, when you talk about a "virtual constructor", client code only knows that it creates an A-derived object (or an A itself), it does explicitly not specify the concrete type, or otherwise the idiom would be pretty pointless. – Christian Hackl Feb 13 at 7:18
  • @ChristianHackl When Derived class object is created Base class constructor is called. But the catch is I don't want to call all of Base class, I want to call only some init() but not other fun(). I have updated the question code. – pokche Feb 13 at 7:26
  • Related. I would scrap this idea in favor of a lazily initialized class, which can be virtualized. – Neil Feb 13 at 7:30
  • 1
    @pokche: I see what your code is doing, but it's just not what people normally think about when they use the word "virtual constructor". Idioms and patterns have names to make communication of intent easier, therefore I believe your (IMO) wrong name for the whole thing clouds the real issues. – Christian Hackl Feb 13 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.