class AClass
{
private:
int k;
public:
AClass(); //default constructor
AClass dosth(); // random function
};
In the main function:
1 2 3 4 5
int main()
{
AClass a=a.dosth();
return 0;
}
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)
Oh, sorry about that, that is my mistake. Because I wrote the code in the post section, I didn't notice it :D. That's just a random function and it returns a AClass data type.
class Date
{
private:
int d, m, y;
public:
Date();
Date(int Y);
Date(int Y, int M);
Date(int Y, int M, int D);
Date(const Date& src);
Date& operator=(const Date& src);
bool valid();
Date Tomorrow();
Date Yesterday();
Date AddDay(int k);
Date AddMonth(int k);
Date AddYear(int k);
};
void main()
{
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 d5(d2);
Date d6;
d6=d3;
d6=d3.Tomorrow();
d5=d2.Yesterday();
int k=7;
Date d7=d7.AddDay(k); //My problem is here, I cannot initialize d7
d6=d2.AddMonth(k);
d2=d1.AddYear(k);
//More function.....
}
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:
1 2
Date d7; // constructs d7
d7 = d7.AddDay(k); // now call AddDay