Subscribe to Invariance_Under_Translation        RSS Feed
-----

Composition

Icon Leave Comment
When creating classes, we aim to have each class perform one function. For more complex problems, one solution is to use composition. I use the ol' computer example. A computer performs many operations. It directs the flow of data, saves and retrieves data, provides a UI for input/output. Instead of writing one giant class for handling all of these operations, we could break this into multiple classes that handle objects between eachother. Below are three files that represent a simple example of such. There is main.cpp which provides the UI, CPU.h which directs objects to they're proper class, and Storage.h which accepts the data in this scenario. This is a simple example, but it gives you an idea of how Composition can make your complex class more simple to maintain through sub-classes.

main.cpp
//Composition
#include<iostream>
#include<string>
#include<stdlib.h>

#include"CPU.h"


using namespace std;


int main()
{

	int val = 0;
	string choice;

	for(int j = 0; j < 5; j++)
	{
		cout<<"Booting..."<<endl;
	}
	cout<<"Boot Success!"<<endl;
	cout<<endl;
	cout<<"\nPress any key to continue..."<<endl;
	cin.get();

	system("CLS");
	cout<<endl;
	cout<<"Welcome User, you may now store numerical data."<<endl;
	cout<<endl;

	do
	{
	cout<<endl;
	cout<<"Please enter a number to save to disk."<<endl;
	cout<<endl;

	if(!(cin>>val))
	{
		cout<<endl;
		cout<<"Invalid Input"<<endl;
		return 0;
	}
	else
	cout<<endl;

	
		cout<<"Saving..."<<endl;
		cout<<endl;

	CPU beginProc((Storage(val)));  //explicitly initialize CPU
	cout<<endl;		        //to pass val to class Storage

	cout<<"Would you like to save another number? (y or n)"<<endl;
	cout<<endl;

	cin>>choice;
	
	system("CLS");
	
	}while(choice=="y");

	cout<<endl;
	cout<<"Goodbye"<<endl;
	cout<<endl;

	cin.get();
	return 0;

}



CPU.h
#ifndef CPU_H
#define CPU_H

#include<iostream>

#include"Storage.h" //Must include Storage.h to allow 
		    //passing of object from CPU
class CPU
{

	Storage objPass;

public:

	CPU(){};
	CPU(const Storage &obj) : objPass(obj) //creating a reference to 
	{					//storage class, allow initialization
	}					//of passed object to storage 

	~CPU()
	{
	}

};



#endif



Storage.h
#ifndef STORAGE_H
#define STORAGE_H

#include<iostream>

class Storage
{
	int store;

public:

	Storage() : store(0)
	{
	}
	Storage(int passIn) : store(passIn) //Since an int was passed out of
	{				    //main(), we accept an int in storage
		std::cout<<store<<" has been saved to disk.\n";
	}

	~Storage(){};

};




#endif

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2018

S M T W T F S
1234567
891011121314
1516 17 18192021
22232425262728
293031    

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)