TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: FRANK MASINGILL
from: CLIFF RHODES
date: 1997-05-12 21:40:00
subject: Creating workable subcla

--> Frank Masingill wrote to All  <--
 
FM>class Compute
FM>{
FM>    private:
FM>        int Num1, Num2;        //private data members
FM>    public:
FM>        Compute(int, int);       //constructor function
FM>        ~Compute();              //destructor function
FM>        int Sum(void);           //member function to compute sum
FM>};
 
FM>    This works.  Now what I would like to do is to modify it so as
FM>to have a subclass ADD to get this same result and then a subclass
FM>SUBTRACT to subtract the same two numbers.  I think this will help
FM>me to understand the relationships and then I can use the
FM>pattern to extend to dividing and multiplication.
 
Frank, you do not need subclasses. You should add member functions
Add() and Subtract(). Their form would look exactly like your Sum()
member.
 
Inside class definition after int Sum(void); put:
   int Add(void);
   int Subtract(void);
 
Then add to code:
int Compute::Add(void)
{
   return Num1 + Num2;
}
 
int Compute::Subtract(void)
{
   return Num1 - Num2;
}
 
Also, in this case you could drop the destructor. Since you don't have
any cleaning up to do, don't put a destructor--just let the compiler
create a default destructor for you.
 
If you wanted to use a destructor, you might consider using new to
allocate space for Num1 and Num2 in the constructor. Then you can call
delete in the destructor. Num1 and Num2 would have to be pointers in 
this case. You might want to try it that way just for the experience 
although the way you are currently doing it is more efficient.
 
A more interesting exercise would be to create a class Number and then
write code to add/subtract objects of type Number. You could do this
with member functions or, better still, by overloading the +/-
operators.
 
Cliff Rhodes
cliff.rhodes@juge.com
 
X CMPQwk 1.42 1692 X"Philosophy is language idling." - Ludwig Wittgens
--- Maximus/2 3.01
---------------
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.