Reputation: 133
This is correct code from a classmate the professor bragged about and I cant understand why it requires a double constructor i originally only had the first function and couldnt figure out it required two which lagged my progress as a professional
class Studentrecords
{
private:
struct student
{
string name;
string address;
int ID;
double gpa;
};
student *stackArray;
int stackSize;
int top;
public:
Studentrecords();
Studentrecords(int size);
~Studentrecords();
void push(string name, string address, int id, double gpa);
void pop();
bool isFull() const;
bool isEmpty() const;
void display();
};
Studentrecords::Studentrecords(int size)
{
stackArray = new student[size];
top = 0;
}
Studentrecords::Studentrecords()
{
stackSize = 25;
stackArray = new student[stackSize];
top = 0;
}
Studentrecords::~Studentrecords()
{
delete [] stackArray;
}
Upvotes: 0
Views: 13167
Reputation: 227588
The second constructor allows you to initialize a StudentRecords
to a given size. This is convenient, but not strictly necessary. Unfortunately, is also allows an implicit conversion from int to StudentRecords
, which you can disable by making it explicit
.
explicit Studentrecords(int size);
That will prevent nonsense such as
StudentRecords s = 4*5;
A more important fact is that your class deals with dynamically allocated resources, so you must follow the rule of three and provide a copy constructor and a copy assignment operator, besides the destructor that you have already provided.
Upvotes: 4
Reputation: 182885
The code doesn't require two constructors. A single constructor with a default argument is better. And the first constructor is broken, since it fails to set stackSize
.
Upvotes: 0
Reputation: 258678
It doesn't require two constructors, that's just how the class is defined. That way, you can create an object in two ways:
Studentrecords s(15);
which will create a Studentrecords
object of size 15, or
Studentrecords s;
which will call the default constructor, and create an object of type Studentrecords
and size 25.
I must note that this is bad code though:
Studentrecords()
constructor can be replaced with Studentrecords(int size = 25)
to avoid code duplication.std::vector
.Upvotes: 7