hi, quick question out of the book that I wouldn't even know where to start.
A class called Calendar has a default constructor and a constructor that accepts an integer value specifying the year. Write a code segment invoking EACH of the constructors for an object called primary. Use the current year as the argument to the second constructor.
Any help would be appreciated. :)
Copyright © 2024 Q2A.ES - All rights reserved.
Answers & Comments
In object oriented programming languages, like C++ and Java, classes are able to have one constructor, multiple constructors, or even no constructor at all, and will still work properly, provided the associated objects are instantiated and used properly.
In the case of the "Calendar" class that has two constructor functions, one that takes no parameters and one that takes an integer value as a parameter, this is called "function (or method) overloading", which simply allows a class to be set up in multiple ways, depending on what is needed by the program, etc.
Since the "Calendar" class has a default constructor, you can invoke this constructor function by simply declaring and instantiating an object of the "Calendar" class, called "primary", without including any parameters in the constructor function's parameter list, like in the code below:
Calendar primary(); //default constructor function (no parameters)
If you would like to invoke the "Calendar" class' overloaded constructor function that takes an integer value as a parameter, you can do this much like we did above, but instead of leaving the constructor's parameter list blank, we can include an integer (in this case, the current year), as seen below:
Calendar primary(2014); //overloaded constructor function (passing an int as a param)
Also, like Jeff said, you cannot instantiate two objects with the same name, even if you use two different constructor functions in doing so, as this will cause an error.
However, you can create different objects with different names, using whichever constructor function you like that is contained within the class, and this should work without any issues!
Another thing that you should note is that if you have a class where there is no constructor method implicitly stated within the class, the class' default constructor function or method will be invoked when an object of that class is instantiated. (This will essentially "do nothing" that you will notice, especially if you do not require the use of a constructor function in your class, but will still occur nonetheless.)
For more information about constructor functions, I would suggest that you check out the two links that are provided in the "Sources" section of this answer, which is where I got some of the information I used in this answer from!
Best of luck and I hope I helped you!
Calendar primary();
Calendar primary(2014);
you can't use them together though