0

I want to do a pre-processing activity before I pass a value to an initialization list.

(for example: to do assertion checking)

Here's some context to my question: suppose I have,

1.    class B {
2.    private:
3.         int b_value;
4.    public:
5.         B(int input_of_b) {
6.             b_value = input_of_b;
7.        }
8.    };

and

9.   
10.    class A {
11.    private:
12.        int a_value;
13.        B b_obj
14.    public:
15.         A(int input_value) : b_obj(input_value) {
16.             //A constructor gets called after init list happens
17.        }
18.    };

what if, at line 15; just before I call initialization list to initialize b_obj (b_value) - to input_value

I want to manipulate (do checking or some pre-processing ) the value of input_value ??

How do I achieve this? In Java - there would be something like an initialization block.

I have already thought of -

  1. Making a function external to class A and B, and just before creating an object of A, and initializing it with "input_value", pre-process that value. (However, this violates the loose-coupling concept)

  2. Making a parent class "A's parent" to class A, make class A extend it, do pre-processing in that class, since parent constructor gets called before initialization list? I've not tried this, and I'm not sure if it is the right approach.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jm'
  • 107
  • 9
  • 1
    You might have a staitic member function int preprocess(int) and initialize via b_obj(preprocess(input)) –  Mar 25 '14 at 13:44
  • 1
    Sounds like it should be responsibility of `B` to mantain correct value of that int. So why not do it in B's constructor? – jrok Mar 25 '14 at 13:47
  • @jrok, that may not always be possible, especially if it's part of a library for example – galdin Apr 02 '14 at 11:55

3 Answers3

1

I solved this by

making B a pointer, preprocessing the value, and then initializing the B object using new, and then deallocate memory in the destructor

i.e.

10.    class A {
11.    private:
12.        int a_value;
13.        B* b_obj
14.    public:
15.         A(int input_value) {
16.            //preprocess input_value here
17.            b_obj = new B(input_value);
18.         }
19.         ~A(){
20.            delete b_obj;
21.         }
22.    };
galdin
  • 12,411
  • 7
  • 56
  • 71
jm'
  • 107
  • 9
0

As far as I understand your question, I think you must try to manipulate input in a's constructor and then from that constructor call b's constructor with that input.

0

Do it in a function!

int b_validate(int);

A::A(int input_value)
    : b_obj(b_validate(input_value))
{}

Also, I'm not initializing a_value because you should remove it instead.

user2394284
  • 5,520
  • 4
  • 32
  • 38