I have to write a program based of this header file and I can't even get the constructor right. Will someone show me how to do it? Thanks.
// File: Peg.h
/// Class Peg from Main and Savage
//
// provides a "peg" that can hold a maximium of 64 disks
// of sizes 1 to MAX_INT in diameter.
//
// CONSTRUCTOR: Peg(x)
// POSTCONDITION the Peg has been initialized to have x disks of size x to size 1
// on the peg
//
// CONSTANT functions:
//
// size_t count ();
// POSTCONDITIONS: the number of disks on the Peg is returned
//
// Disk top_Disk ();
// PRECONDITIONS: the Peg is not empty
// POSTCONDITIONS: the disk at the top of the Peg is returned
//
//
// MODIFICATION functions:
//
// void add (const Disk added_Disk);
// PRECONDITIONS: the Peg is not full AND the added_Disk is smaller than the top disk
// POSTCONDITIONS: the Peg has the disk added to the top of the peg
//
// void remove ();
// PRECONDITIONS: the Peg is not empty
// POSTCONDITIONS: the top disk is removed from the Peg
//
// FRIENDS
// operator <<
// POSTCONDITIONS: the disk on the peg are printed from the bottom to the top
//
You define a constructor like any other function, except a ctor doesn't want the return type written before itself
If you want you can define it inside the class declaration like this
1 2 3 4 5 6 7 8 9 10
class Peg
{
public:
typedef std::size_t Disk;
Peg(std::size_t init_disks=64)
{
// Your instructions here
}
// Etc
};
Or you can use a dedicated cpp file. The definition goes like this
1 2 3 4 5 6
#include "Header_of_the_class.h"
Class_name::Function_name(parameters)
{
// Your instructions here
}
Note that you have to NOT write any return type. Ctors and dtors never return anything.
Since a constructor has the same name as the class Function_name and Class_name will be identical