I am coming from the Java background. I have the following program.
#include <string>
#include <iostream>
class First {
public:
First(int someVal): a(someVal) {
}
int a;
};
class Second {
public:
First first;
Second() { // The other option would be to add default value as ": first(0)"
first = First(123);
}
};
int main()
{
Second second;
std::cout << "hello" << second.first.a << std::endl;
}
In class Second
, I wanted to variable first
to remain uninitialized until I specifically initialize it in Second()'s constructor
. Is there a way to do it? Or am I just left with 2 options?:
- Provide a parameter-less constructor.
- Initialize it with some default value and later re-assign the required value.
I can't initialize first
in the initializer-list with the right value, since the value is obtained after some operation. So, the actual required value for first
is available in Second()
constructor only.
first
will be initialized as soon as you instantiate aSecond
. There's no way around that. All you can do is change its value at a later stage. – GirdSecond() : first(0) { first = First(123); }
– Jennettefirst
in the parameter list still. Use a function. – Devourfirst
yet inSecond
's constructor you are initializing it anyway? Setfirst
to be a pointer and set it toNULL
ornullptr
for C++11 in your constructor. Then at a later stage usenew First(arg)
to create a new pointer to an object of First type – Arianismunique_ptr
orshared_ptr
, depending on what d-tor, assignment, and copy should do. – Fluorocarbon