Hello, I am new to C++ and have been reviewing the forum and watching video tutorials to assist me in creating a constructor for my program listed below, that will print (1,1) if the user hits the enter key without entering an number. I have made a few attempts but currently the 1,1 prints at program execution. Any guidance provided would be greatly appreciated.
cout <<"The sum of two complex numbers is ("<<realPart3<<","<<imaginaryPart3<< ") and the difference is ("<<realPart4<<","<<imaginaryPart4<<")";
cout << "\n";
The constructor will be called when the object is created. In that case at the beginning of the program. If you want it later you need another function.
class RealImag
{
private:
// You only need these two variables
double realPart;
double imaginaryPart;
public:
// For explanation look below
RealImag(double realArg = 1.1, double imagArg = 1.1)
{
setReal(realArg);
setImaginary(imagArg);
}
void setReal(double realArg)
{
if (realArg > 0.0)
{ realPart = realArg; }
}
void setImaginary(double imagArg)
{
if (imagArg > 0.0)
{ imaginaryPart = imagArg; }
}
// --- rest of your code ---
};
Default arguments are given, remeber, if you assign a default value for one parameter, you have to provide it for all the others as well.
If you don't, a message similar to this: 'RealImag::RealImag': missing default parameter for parameter 1/2 will be output and the code will not compile. The reason this works is that a default constructor is a constructor that either has no parameters, or if there are parameters, they all have to have default values.
Otherwise the compiler will complain that there is no default constructor. And in such case, you would explicitly have to provide your default constructor:
RealImag()
{ realPart = 0; imagPart = 0; }
To be able to define your class object without passing any parameters to it.
RealImag img;
In case the constructor is written as demonstrated above, you can do this:
1 2 3 4 5 6 7
RealImag nums;
cout << "Enter a complex number separated by a space (Ex: 1.7 2.4): ";
cin >> realOne >> imaginaryOne;
nums.setReal(realOne);
nums.setImaginary(imaginaryOne);
Thank you both for your input. I am working on modifying my code to accommodate your suggestions. Seeing it laid out definitely helps to make the mental connection.