AClass(); //default constructor
AClass dosth(); // random function
In the main function:
1 2 3 4 5
Seems like the compiler will run the dosth function before the constructor, but I want the constructor to run first. I cannot edit the code in the main function because the main function is given by my teacher. Anything I can do?
This code would not compile, as dosth returns void, not an AClass. Can you post the actual code you're using to call dosth? The only way it would call it first was if you are using an incomplete object (which really can only happen if you have a bad pointer)
int d, m, y;
Date(int Y, int M);
Date(int Y, int M, int D);
Date(const Date& src);
Date& operator=(const Date& src);
Date AddDay(int k);
Date AddMonth(int k);
Date AddYear(int k);
Date d1; // Current date: 2/11/2012
Date d2(2012); // 1/1/2012;
Date d3(2012, 8); // 01/08/2012
Date d4(2012, 10, 17); // 17/10/2012
Date d7=d7.AddDay(k); //My problem is here, I cannot initialize d7
Hrm... I'm surprised this compiles, but I guess I can see why it would.
Okay this line is your problem. You are constructing d7 with the output of d7.AddDay, so it cannot construct d7 without first calling AddDay, but it can't call AddDay with a constructed d7. See the problem?
I would've thought this would give you a compiler error, but maybe it doesn't. Huh.
The easiest solution is to just call the ctor first:
Date d7; // constructs d7
d7 = d7.AddDay(k); // now call AddDay