Return to the C++ Demos Home Page

SAMS Teach Yourself C++ in 21 Days

Chapter Six

 Prog 1 : Simple use of classes and a header w/ declarations

// chap6p1 - uses cat.hpp and shows how to use a class
// 
// first we define the methods, then we use the class 
// by declaring an instance of it and toolin around
//

// Chap 6 of Sams TYC++ in 21
//
// because of Visual C++ this works, but I'm using a class 
// with it's definitions in a .hpp file and haven't even 
// included it.  Because "cat.hpp" is in the project header 
// files it lets me do it.....Bad form

// #include "cat.hpp"     <----  should be there 

// include the cat class def.....
#include "cat.hpp"        <-----  now it is  
int main()
{

   Cat Johnny(5);    // creates an instance of Cat called "Johnny"
   Cat Lars(33);

   Johnny.Meow();  // uses Meow() method

   cout << "Johnny is a cat who's " << Johnny.GetAge() << " years old.\n"; // uses accessor
   
   Johnny.Meow();  // Still works!!

   Johnny.SetAge(7);  // uses accessor to set age....

   cout << "Now Johnny is a cat who's " << Johnny.GetAge() << " years old.\n";
   cout << "Now Lars is a cat who's " << Lars.GetAge() << " years old.\n";	
  
// done
return 1;
}
******** The cat.hpp file ***************
// Header file for the "Cat" class used in chap6p1.cpp
//

#include <iostream.h>  // Nested includes?

class Cat
{
   public:
       Cat(int initialAge);
	   ~Cat();
	   int GetAge();
	   void SetAge(int age);
	   void Meow();
   private:
       int itsAge;
};

// defining methods in the HPP file.....
// constructor of Cat
Cat::Cat(int initialAge)
{
	itsAge = initialAge;
}
// destructor (no action)
Cat::~Cat()
{
}
// GetAge  a public accessor method
int Cat::GetAge()
{
	return itsAge;
}
// SetAge  lets user set cats age
void Cat::SetAge(int age)
{
	itsAge = age;
}
// Meow  Just prints Meow to the screen
void Cat::Meow()
{
	cout << "..Meow!!..\n";
} // End of class Cat
  

Return to the C++ Demos Home Page