Code:
// File: hello.h Greetings class specification
#ifndef HELLO_H
#define HELLO_H
class greetings{
public:
greetings(const char*); // constructor
~greetings(void); // destructor
private:
char *ModuleString; // string to print
};
#endif
Code:
// File: hello.cpp Source code for greetings objects
#include <iostream.h>
#include <string.h>
#include "hello.h"
// Explicit constructor prints greetings and string argument, which it stores in data member
// Pre: str is a string.
// Post: The object greetings has been constructed and a welcome message printed
greetings::greetings(const char *str)
{
ModuleString = new char[strlen(str) + 1];
strcpy(ModuleString, str);
cout<<"Welcome to "<<str<<"!\n";
}
// Destructor prints exit greetings and string argument and deletes area to which data member points
// Pre: none.
// Post: A good-bye message has been printed and the object has been destroyed.
greetins::~greetings(void)
{
cout<<"Good-bye from "<<ModuleString<<".\n";
delete [] ModuleString;
}
Code:
// Program to test greetings class
#include <iostream.h>
#include "hello.h"
void subprog(void);
int main(void)
{
greetings hi("main");
cout<<" main: statements before the call to subprog\n";
subprog();
cout<<" main: statements after the call to subprog\n";
return 0;
}
// Function to create an instance of the greetings class
// Pre: none
// Post: A greetings object has been created and destroyed
void subprog(void)
{
greetings s("subprog");
cout<<" subprog: statements in subprog\n";
}