There is an issue with my code. I created a simple class that has a constructor with default arguments. I understand that if I don't pass in any arguments to the constructor, the default values will take over, otherwise they will be overwritten by the parameters. Here is the code of my class:
// This class models a person
class Person {
public:
// Constructor
Person(string name = "noname", int age = 0, char gender = 'U')
: name_(name),
age_(age),
gender_(gender) {
}
// Accessor for name_
const string& name() const {
return name_;
}
// Accessor for age_
int age() const {
return age_;
}
// Accessor for gender_
char gender() const {
return gender_;
}
// Mutator for name_
void set_name(const string& name) {
name_ = name;
}
// Mutator for age_
void set_age(int age) {
age_ = age;
}
// Mutator for gender_
void set_gender(char gender) {
gender_ = gender;
}
// Returns a string representation of our person
string ToString() {
ostringstream ss;
// Add our base ToString to the stream
ss << name_ << "\nAge: " << age_ << "\nGender: " << gender_ << endl;
return ss.str();
}
private:
string name_;
int age_;
char gender_;
};
// Program starts here
int main() {
// Create an instance of our base class
Person me("Abraham Lincoln", 56, 'M');
cout << me.ToString() << endl;
// Calls the default constructor.
Person someone;
cout << someone.ToString() << endl;
// This is a pun.
Person sometwo();
cout << sometwo.ToString() << endl;
// This ends our program
return 0;
}
The first example initializes the object with the passed in arguments. The second example creates an object, and since no arguments are passed in, the default values take over. And calling the toString() function indeed confirms this. Now when I create the second example, I get a compilation error:
base_main.cpp: In function ‘int main()’:
base_main.cpp:24:19: error: request for member ‘ToString’ in ‘sometwo’, which is of non-class type ‘Person()’
cout << sometwo.ToString() << endl;
^
What's this? It's interesting that if I comment out the line // cout << sometwo.ToString() << endl;
the error is removed. So the issue is not in the constructor. How do I read this error exactly? What is a non-class type 'Person()'
?
I understand that down the forms below are synonyms, they call the constructor with the default arguments. The first one just calls the constructor implicitly, but the second one calls the constructor explicitly without passing in any arguments. Am I right or not?
Person person1;
Person person2();