In: Computer Science
Code in C++. Using ONE of the following themes to create a class and demonstrate the idea. Use this to create a solution (two ADTs and a driver program) to demonstrate the following concepts. Create a one page summary to describe where you are using each of these concepts.
Themes:(PICK ONE)
Concepts to include:
ANSWER :-
GIVEN THAT :-
USING THE THEME------- A HOUSE HAS A DOOR(USING C++)
Composition (HAS-A) is achieved by the use of instance variables that are references to other objects.
****For example: a house has a door.
Let we define two abstract data seperately for house and door using the classes as ADT in c++
PROGRAM :-
#include <utility> //Utility class
#include <iostream>
#ifndef HOUSE_H //let there be a header class House.h
#define HOUSE_H //Include guards avoiding double inclusion of the
header file
using namespace std;
public class House { //classname
private String location; //data members
private static int doors; //static data member
public House()
{
}
public House(String location,int doors ){ //constructor with
default arguments
this.location=location;
this.doors=doors;
}
public String getLocation() { //member functions
return location;
}
public void setLocation(String location) {
this->location = location; //this pointer using arrow
operator
}
public static int getNoOfDoors() const { //constant function
return doors; //cannot modify any data member of this object
}
public static void setNoOfDoors(int doors) {
this.doors = abs(doors); //abs is a utility function for absolute
value
}
public ~House(){ //Default destructor that does nothing
}
}
public class Door {
//composition has-a relationship
private House house;
public Door(){ //Constructor
this.house=new House();
house.setNoofDoors(10);
}
public int getNoOfDoors() {
return house.getNoOfDoors();
}
public getA()
{
cout <<"\nA"<<endl;
return *this;
}
public getB()
{
cout <<"\nB"<<endl;
return *this;
}
}
//Here is a driver program for composition that uses door object and calculate the total no. of doors in a house.
public class CheckForDoors {
int main() {
Door door();
int noofdoors = door.getNoOfDoors();
cout <<noofdoors<<endl;
door.getA().getB();
}
}
OUTPUT:-
10
A
B