default constructor help
making a class, don't know how to make the default constructor
#include <iostream>
using namespace std;
class School, 3 member variables that are private
now i need a default constructor for the class with id = 0, hours = 0, days= 0
1 2 3 4 5 6 7 8 9
|
class School
{
private:
int id;
float hours;
int days;
};
|
Do you know how to write a non-default constructor?
no i don't
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
using namespace std;
class School
{
private:
int id;
float hours;
int days;
public:
School();
};
School::School()
{
id = 0;
hours = 0;
days = 0;
}
int main()
{
system("pause");
return 0;
}
|
?
Yes, that is the correct way to write a default ctor. Good work.
A better way would be with initialization list:
16 17 18 19
|
School::School()
: id ( 0 ), hours ( 0 ), days ( 0 )
{
}
|
Topic archived. No new replies allowed.