[try Beta version]
Not logged in

 
Inheritence / function help

Feb 9, 2012 at 11:25am
class house
{
char type;
}
class flat:house
{
int rooms
}
class detact:house
{
int rooms;
}
class old:house
{
int rooms;
}


How would i go about storing these rooms in a single array without have loads of if statements like if detact is first type the room would be like room[0]; and if old is second it would be like room[1];
Feb 9, 2012 at 2:34pm
Your array would contain elements who type are pointers to houses. You need to make an interface for house that all derived classes would then inherit and implement (if they need to do different things). This is how you get rid of the if statements, if you don't provide an inheritable interface you will still be checking types.

e.g.

1
2
3
4
5
class house
{
   //...
   virtual int getSquareFootage()const=0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class flat : public house
{
   //...
   int getSquareFootage()const
   {
      return 10; //simple example
   }
}

class old: public house
{
   //...
   int getSquareFootage()const
   {
      return 15; //simple example
   }
}


1
2
3
4
5
6
7
8
//... Main()
{
   for(...)
   {
       myHouses[i]->getSquareFootage(); 
   }
   //...
}
Topic archived. No new replies allowed.